]> granicus.if.org Git - postgresql/blob - src/backend/postmaster/pgstat.c
Move pgstat.tmp into a temporary directory under $PGDATA named pg_stat_tmp.
[postgresql] / src / backend / postmaster / pgstat.c
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-2008, PostgreSQL Global Development Group
15  *
16  *      $PostgreSQL: pgsql/src/backend/postmaster/pgstat.c,v 1.178 2008/08/05 12:09:30 mha Exp $
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_POLL_H
32 #include <poll.h>
33 #endif
34 #ifdef HAVE_SYS_POLL_H
35 #include <sys/poll.h>
36 #endif
37
38 #include "pgstat.h"
39
40 #include "access/heapam.h"
41 #include "access/transam.h"
42 #include "access/twophase_rmgr.h"
43 #include "access/xact.h"
44 #include "catalog/pg_database.h"
45 #include "catalog/pg_proc.h"
46 #include "libpq/ip.h"
47 #include "libpq/libpq.h"
48 #include "libpq/pqsignal.h"
49 #include "mb/pg_wchar.h"
50 #include "miscadmin.h"
51 #include "pg_trace.h"
52 #include "postmaster/autovacuum.h"
53 #include "postmaster/fork_process.h"
54 #include "postmaster/postmaster.h"
55 #include "storage/backendid.h"
56 #include "storage/fd.h"
57 #include "storage/ipc.h"
58 #include "storage/pg_shmem.h"
59 #include "storage/pmsignal.h"
60 #include "utils/guc.h"
61 #include "utils/memutils.h"
62 #include "utils/ps_status.h"
63 #include "utils/rel.h"
64 #include "utils/tqual.h"
65
66
67 /* ----------
68  * Paths for the statistics files (relative to installation's $PGDATA).
69  * ----------
70  */
71 #define PGSTAT_STAT_PERMANENT_FILENAME          "global/pgstat.stat"
72 #define PGSTAT_STAT_PERMANENT_TMPFILE           "global/pgstat.tmp"
73 #define PGSTAT_STAT_FILENAME                            "pg_stat_tmp/pgstat.stat"
74 #define PGSTAT_STAT_TMPFILE                                     "pg_stat_tmp/pgstat.tmp"
75
76 /* ----------
77  * Timer definitions.
78  * ----------
79  */
80 #define PGSTAT_STAT_INTERVAL    500             /* How often to write the status file;
81                                                                                  * in milliseconds. */
82
83 #define PGSTAT_RESTART_INTERVAL 60              /* How often to attempt to restart a
84                                                                                  * failed statistics collector; in
85                                                                                  * seconds. */
86
87 #define PGSTAT_SELECT_TIMEOUT   2               /* How often to check for postmaster
88                                                                                  * death; in seconds. */
89
90
91 /* ----------
92  * The initial size hints for the hash tables used in the collector.
93  * ----------
94  */
95 #define PGSTAT_DB_HASH_SIZE             16
96 #define PGSTAT_TAB_HASH_SIZE    512
97 #define PGSTAT_FUNCTION_HASH_SIZE       512
98
99
100 /* ----------
101  * GUC parameters
102  * ----------
103  */
104 bool            pgstat_track_activities = false;
105 bool            pgstat_track_counts = false;
106 int                     pgstat_track_functions = TRACK_FUNC_OFF;
107 int                     pgstat_track_activity_query_size = 1024;
108
109 /*
110  * BgWriter global statistics counters (unused in other processes).
111  * Stored directly in a stats message structure so it can be sent
112  * without needing to copy things around.  We assume this inits to zeroes.
113  */
114 PgStat_MsgBgWriter BgWriterStats;
115
116 /* ----------
117  * Local data
118  * ----------
119  */
120 NON_EXEC_STATIC int pgStatSock = -1;
121
122 static struct sockaddr_storage pgStatAddr;
123
124 static time_t last_pgstat_start_time;
125
126 static bool pgStatRunningInCollector = false;
127
128 /*
129  * Structures in which backends store per-table info that's waiting to be
130  * sent to the collector.
131  *
132  * NOTE: once allocated, TabStatusArray structures are never moved or deleted
133  * for the life of the backend.  Also, we zero out the t_id fields of the
134  * contained PgStat_TableStatus structs whenever they are not actively in use.
135  * This allows relcache pgstat_info pointers to be treated as long-lived data,
136  * avoiding repeated searches in pgstat_initstats() when a relation is
137  * repeatedly opened during a transaction.
138  */
139 #define TABSTAT_QUANTUM         100 /* we alloc this many at a time */
140
141 typedef struct TabStatusArray
142 {
143         struct TabStatusArray *tsa_next;        /* link to next array, if any */
144         int                     tsa_used;               /* # entries currently used */
145         PgStat_TableStatus tsa_entries[TABSTAT_QUANTUM];        /* per-table data */
146 } TabStatusArray;
147
148 static TabStatusArray *pgStatTabList = NULL;
149
150 /*
151  * Backends store per-function info that's waiting to be sent to the collector
152  * in this hash table (indexed by function OID).
153  */
154 static HTAB *pgStatFunctions = NULL;
155
156 /*
157  * Tuple insertion/deletion counts for an open transaction can't be propagated
158  * into PgStat_TableStatus counters until we know if it is going to commit
159  * or abort.  Hence, we keep these counts in per-subxact structs that live
160  * in TopTransactionContext.  This data structure is designed on the assumption
161  * that subxacts won't usually modify very many tables.
162  */
163 typedef struct PgStat_SubXactStatus
164 {
165         int                     nest_level;             /* subtransaction nest level */
166         struct PgStat_SubXactStatus *prev;      /* higher-level subxact if any */
167         PgStat_TableXactStatus *first;          /* head of list for this subxact */
168 } PgStat_SubXactStatus;
169
170 static PgStat_SubXactStatus *pgStatXactStack = NULL;
171
172 static int      pgStatXactCommit = 0;
173 static int      pgStatXactRollback = 0;
174
175 /* Record that's written to 2PC state file when pgstat state is persisted */
176 typedef struct TwoPhasePgStatRecord
177 {
178         PgStat_Counter tuples_inserted;         /* tuples inserted in xact */
179         PgStat_Counter tuples_deleted;          /* tuples deleted in xact */
180         Oid                     t_id;                   /* table's OID */
181         bool            t_shared;               /* is it a shared catalog? */
182 } TwoPhasePgStatRecord;
183
184 /*
185  * Info about current "snapshot" of stats file
186  */
187 static MemoryContext pgStatLocalContext = NULL;
188 static HTAB *pgStatDBHash = NULL;
189 static PgBackendStatus *localBackendStatusTable = NULL;
190 static int      localNumBackends = 0;
191
192 /*
193  * Cluster wide statistics, kept in the stats collector.
194  * Contains statistics that are not collected per database
195  * or per table.
196  */
197 static PgStat_GlobalStats globalStats;
198
199 static volatile bool need_exit = false;
200 static volatile bool need_statwrite = false;
201
202 /*
203  * Total time charged to functions so far in the current backend.
204  * We use this to help separate "self" and "other" time charges.
205  * (We assume this initializes to zero.)
206  */
207 static instr_time total_func_time;
208
209
210 /* ----------
211  * Local function forward declarations
212  * ----------
213  */
214 #ifdef EXEC_BACKEND
215 static pid_t pgstat_forkexec(void);
216 #endif
217
218 NON_EXEC_STATIC void PgstatCollectorMain(int argc, char *argv[]);
219 static void pgstat_exit(SIGNAL_ARGS);
220 static void force_statwrite(SIGNAL_ARGS);
221 static void pgstat_beshutdown_hook(int code, Datum arg);
222
223 static PgStat_StatDBEntry *pgstat_get_db_entry(Oid databaseid, bool create);
224 static void pgstat_write_statsfile(bool permanent);
225 static HTAB *pgstat_read_statsfile(Oid onlydb, bool permanent);
226 static void backend_read_statsfile(void);
227 static void pgstat_read_current_status(void);
228
229 static void pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg);
230 static void pgstat_send_funcstats(void);
231 static HTAB *pgstat_collect_oids(Oid catalogid);
232
233 static PgStat_TableStatus *get_tabstat_entry(Oid rel_id, bool isshared);
234
235 static void pgstat_setup_memcxt(void);
236
237 static void pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype);
238 static void pgstat_send(void *msg, int len);
239
240 static void pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len);
241 static void pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len);
242 static void pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len);
243 static void pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len);
244 static void pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len);
245 static void pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len);
246 static void pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len);
247 static void pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len);
248 static void pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len);
249 static void pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len);
250
251
252 /* ------------------------------------------------------------
253  * Public functions called from postmaster follow
254  * ------------------------------------------------------------
255  */
256
257 /* ----------
258  * pgstat_init() -
259  *
260  *      Called from postmaster at startup. Create the resources required
261  *      by the statistics collector process.  If unable to do so, do not
262  *      fail --- better to let the postmaster start with stats collection
263  *      disabled.
264  * ----------
265  */
266 void
267 pgstat_init(void)
268 {
269         ACCEPT_TYPE_ARG3 alen;
270         struct addrinfo *addrs = NULL,
271                            *addr,
272                                 hints;
273         int                     ret;
274         fd_set          rset;
275         struct timeval tv;
276         char            test_byte;
277         int                     sel_res;
278         int                     tries = 0;
279
280 #define TESTBYTEVAL ((char) 199)
281
282         /*
283          * Create the UDP socket for sending and receiving statistic messages
284          */
285         hints.ai_flags = AI_PASSIVE;
286         hints.ai_family = PF_UNSPEC;
287         hints.ai_socktype = SOCK_DGRAM;
288         hints.ai_protocol = 0;
289         hints.ai_addrlen = 0;
290         hints.ai_addr = NULL;
291         hints.ai_canonname = NULL;
292         hints.ai_next = NULL;
293         ret = pg_getaddrinfo_all("localhost", NULL, &hints, &addrs);
294         if (ret || !addrs)
295         {
296                 ereport(LOG,
297                                 (errmsg("could not resolve \"localhost\": %s",
298                                                 gai_strerror(ret))));
299                 goto startup_failed;
300         }
301
302         /*
303          * On some platforms, pg_getaddrinfo_all() may return multiple addresses
304          * only one of which will actually work (eg, both IPv6 and IPv4 addresses
305          * when kernel will reject IPv6).  Worse, the failure may occur at the
306          * bind() or perhaps even connect() stage.      So we must loop through the
307          * results till we find a working combination. We will generate LOG
308          * messages, but no error, for bogus combinations.
309          */
310         for (addr = addrs; addr; addr = addr->ai_next)
311         {
312 #ifdef HAVE_UNIX_SOCKETS
313                 /* Ignore AF_UNIX sockets, if any are returned. */
314                 if (addr->ai_family == AF_UNIX)
315                         continue;
316 #endif
317
318                 if (++tries > 1)
319                         ereport(LOG,
320                         (errmsg("trying another address for the statistics collector")));
321
322                 /*
323                  * Create the socket.
324                  */
325                 if ((pgStatSock = socket(addr->ai_family, SOCK_DGRAM, 0)) < 0)
326                 {
327                         ereport(LOG,
328                                         (errcode_for_socket_access(),
329                         errmsg("could not create socket for statistics collector: %m")));
330                         continue;
331                 }
332
333                 /*
334                  * Bind it to a kernel assigned port on localhost and get the assigned
335                  * port via getsockname().
336                  */
337                 if (bind(pgStatSock, addr->ai_addr, addr->ai_addrlen) < 0)
338                 {
339                         ereport(LOG,
340                                         (errcode_for_socket_access(),
341                           errmsg("could not bind socket for statistics collector: %m")));
342                         closesocket(pgStatSock);
343                         pgStatSock = -1;
344                         continue;
345                 }
346
347                 alen = sizeof(pgStatAddr);
348                 if (getsockname(pgStatSock, (struct sockaddr *) & pgStatAddr, &alen) < 0)
349                 {
350                         ereport(LOG,
351                                         (errcode_for_socket_access(),
352                                          errmsg("could not get address of socket for statistics collector: %m")));
353                         closesocket(pgStatSock);
354                         pgStatSock = -1;
355                         continue;
356                 }
357
358                 /*
359                  * Connect the socket to its own address.  This saves a few cycles by
360                  * not having to respecify the target address on every send. This also
361                  * provides a kernel-level check that only packets from this same
362                  * address will be received.
363                  */
364                 if (connect(pgStatSock, (struct sockaddr *) & pgStatAddr, alen) < 0)
365                 {
366                         ereport(LOG,
367                                         (errcode_for_socket_access(),
368                         errmsg("could not connect socket for statistics collector: %m")));
369                         closesocket(pgStatSock);
370                         pgStatSock = -1;
371                         continue;
372                 }
373
374                 /*
375                  * Try to send and receive a one-byte test message on the socket. This
376                  * is to catch situations where the socket can be created but will not
377                  * actually pass data (for instance, because kernel packet filtering
378                  * rules prevent it).
379                  */
380                 test_byte = TESTBYTEVAL;
381
382 retry1:
383                 if (send(pgStatSock, &test_byte, 1, 0) != 1)
384                 {
385                         if (errno == EINTR)
386                                 goto retry1;    /* if interrupted, just retry */
387                         ereport(LOG,
388                                         (errcode_for_socket_access(),
389                                          errmsg("could not send test message on socket for statistics collector: %m")));
390                         closesocket(pgStatSock);
391                         pgStatSock = -1;
392                         continue;
393                 }
394
395                 /*
396                  * There could possibly be a little delay before the message can be
397                  * received.  We arbitrarily allow up to half a second before deciding
398                  * it's broken.
399                  */
400                 for (;;)                                /* need a loop to handle EINTR */
401                 {
402                         FD_ZERO(&rset);
403                         FD_SET(pgStatSock, &rset);
404                         tv.tv_sec = 0;
405                         tv.tv_usec = 500000;
406                         sel_res = select(pgStatSock + 1, &rset, NULL, NULL, &tv);
407                         if (sel_res >= 0 || errno != EINTR)
408                                 break;
409                 }
410                 if (sel_res < 0)
411                 {
412                         ereport(LOG,
413                                         (errcode_for_socket_access(),
414                                          errmsg("select() failed in statistics collector: %m")));
415                         closesocket(pgStatSock);
416                         pgStatSock = -1;
417                         continue;
418                 }
419                 if (sel_res == 0 || !FD_ISSET(pgStatSock, &rset))
420                 {
421                         /*
422                          * This is the case we actually think is likely, so take pains to
423                          * give a specific message for it.
424                          *
425                          * errno will not be set meaningfully here, so don't use it.
426                          */
427                         ereport(LOG,
428                                         (errcode(ERRCODE_CONNECTION_FAILURE),
429                                          errmsg("test message did not get through on socket for statistics collector")));
430                         closesocket(pgStatSock);
431                         pgStatSock = -1;
432                         continue;
433                 }
434
435                 test_byte++;                    /* just make sure variable is changed */
436
437 retry2:
438                 if (recv(pgStatSock, &test_byte, 1, 0) != 1)
439                 {
440                         if (errno == EINTR)
441                                 goto retry2;    /* if interrupted, just retry */
442                         ereport(LOG,
443                                         (errcode_for_socket_access(),
444                                          errmsg("could not receive test message on socket for statistics collector: %m")));
445                         closesocket(pgStatSock);
446                         pgStatSock = -1;
447                         continue;
448                 }
449
450                 if (test_byte != TESTBYTEVAL)   /* strictly paranoia ... */
451                 {
452                         ereport(LOG,
453                                         (errcode(ERRCODE_INTERNAL_ERROR),
454                                          errmsg("incorrect test message transmission on socket for statistics collector")));
455                         closesocket(pgStatSock);
456                         pgStatSock = -1;
457                         continue;
458                 }
459
460                 /* If we get here, we have a working socket */
461                 break;
462         }
463
464         /* Did we find a working address? */
465         if (!addr || pgStatSock < 0)
466                 goto startup_failed;
467
468         /*
469          * Set the socket to non-blocking IO.  This ensures that if the collector
470          * falls behind, statistics messages will be discarded; backends won't
471          * block waiting to send messages to the collector.
472          */
473         if (!pg_set_noblock(pgStatSock))
474         {
475                 ereport(LOG,
476                                 (errcode_for_socket_access(),
477                                  errmsg("could not set statistics collector socket to nonblocking mode: %m")));
478                 goto startup_failed;
479         }
480
481         pg_freeaddrinfo_all(hints.ai_family, addrs);
482
483         return;
484
485 startup_failed:
486         ereport(LOG,
487           (errmsg("disabling statistics collector for lack of working socket")));
488
489         if (addrs)
490                 pg_freeaddrinfo_all(hints.ai_family, addrs);
491
492         if (pgStatSock >= 0)
493                 closesocket(pgStatSock);
494         pgStatSock = -1;
495
496         /*
497          * Adjust GUC variables to suppress useless activity, and for debugging
498          * purposes (seeing track_counts off is a clue that we failed here). We
499          * use PGC_S_OVERRIDE because there is no point in trying to turn it back
500          * on from postgresql.conf without a restart.
501          */
502         SetConfigOption("track_counts", "off", PGC_INTERNAL, PGC_S_OVERRIDE);
503 }
504
505 /*
506  * pgstat_reset_all() -
507  *
508  * Remove the stats file.  This is currently used only if WAL
509  * recovery is needed after a crash.
510  */
511 void
512 pgstat_reset_all(void)
513 {
514         unlink(PGSTAT_STAT_FILENAME);
515         unlink(PGSTAT_STAT_PERMANENT_FILENAME);
516 }
517
518 #ifdef EXEC_BACKEND
519
520 /*
521  * pgstat_forkexec() -
522  *
523  * Format up the arglist for, then fork and exec, statistics collector process
524  */
525 static pid_t
526 pgstat_forkexec(void)
527 {
528         char       *av[10];
529         int                     ac = 0;
530
531         av[ac++] = "postgres";
532         av[ac++] = "--forkcol";
533         av[ac++] = NULL;                        /* filled in by postmaster_forkexec */
534
535         av[ac] = NULL;
536         Assert(ac < lengthof(av));
537
538         return postmaster_forkexec(ac, av);
539 }
540 #endif   /* EXEC_BACKEND */
541
542
543 /*
544  * pgstat_start() -
545  *
546  *      Called from postmaster at startup or after an existing collector
547  *      died.  Attempt to fire up a fresh statistics collector.
548  *
549  *      Returns PID of child process, or 0 if fail.
550  *
551  *      Note: if fail, we will be called again from the postmaster main loop.
552  */
553 int
554 pgstat_start(void)
555 {
556         time_t          curtime;
557         pid_t           pgStatPid;
558
559         /*
560          * Check that the socket is there, else pgstat_init failed and we can do
561          * nothing useful.
562          */
563         if (pgStatSock < 0)
564                 return 0;
565
566         /*
567          * Do nothing if too soon since last collector start.  This is a safety
568          * valve to protect against continuous respawn attempts if the collector
569          * is dying immediately at launch.      Note that since we will be re-called
570          * from the postmaster main loop, we will get another chance later.
571          */
572         curtime = time(NULL);
573         if ((unsigned int) (curtime - last_pgstat_start_time) <
574                 (unsigned int) PGSTAT_RESTART_INTERVAL)
575                 return 0;
576         last_pgstat_start_time = curtime;
577
578         /*
579          * Okay, fork off the collector.
580          */
581 #ifdef EXEC_BACKEND
582         switch ((pgStatPid = pgstat_forkexec()))
583 #else
584         switch ((pgStatPid = fork_process()))
585 #endif
586         {
587                 case -1:
588                         ereport(LOG,
589                                         (errmsg("could not fork statistics collector: %m")));
590                         return 0;
591
592 #ifndef EXEC_BACKEND
593                 case 0:
594                         /* in postmaster child ... */
595                         /* Close the postmaster's sockets */
596                         ClosePostmasterPorts(false);
597
598                         /* Lose the postmaster's on-exit routines */
599                         on_exit_reset();
600
601                         /* Drop our connection to postmaster's shared memory, as well */
602                         PGSharedMemoryDetach();
603
604                         PgstatCollectorMain(0, NULL);
605                         break;
606 #endif
607
608                 default:
609                         return (int) pgStatPid;
610         }
611
612         /* shouldn't get here */
613         return 0;
614 }
615
616 void
617 allow_immediate_pgstat_restart(void)
618 {
619         last_pgstat_start_time = 0;
620 }
621
622 /* ------------------------------------------------------------
623  * Public functions used by backends follow
624  *------------------------------------------------------------
625  */
626
627
628 /* ----------
629  * pgstat_report_stat() -
630  *
631  *      Called from tcop/postgres.c to send the so far collected per-table
632  *      and function usage statistics to the collector.  Note that this is
633  *      called only when not within a transaction, so it is fair to use
634  *      transaction stop time as an approximation of current time.
635  * ----------
636  */
637 void
638 pgstat_report_stat(bool force)
639 {
640         /* we assume this inits to all zeroes: */
641         static const PgStat_TableCounts all_zeroes;
642         static TimestampTz last_report = 0;
643
644         TimestampTz now;
645         PgStat_MsgTabstat regular_msg;
646         PgStat_MsgTabstat shared_msg;
647         TabStatusArray *tsa;
648         int                     i;
649
650         /* Don't expend a clock check if nothing to do */
651         /* Note: we ignore pending function stats in this test ... OK? */
652         if (pgStatTabList == NULL ||
653                 pgStatTabList->tsa_used == 0)
654                 return;
655
656         /*
657          * Don't send a message unless it's been at least PGSTAT_STAT_INTERVAL
658          * msec since we last sent one, or the caller wants to force stats out.
659          */
660         now = GetCurrentTransactionStopTimestamp();
661         if (!force &&
662                 !TimestampDifferenceExceeds(last_report, now, PGSTAT_STAT_INTERVAL))
663                 return;
664         last_report = now;
665
666         /*
667          * Scan through the TabStatusArray struct(s) to find tables that actually
668          * have counts, and build messages to send.  We have to separate shared
669          * relations from regular ones because the databaseid field in the message
670          * header has to depend on that.
671          */
672         regular_msg.m_databaseid = MyDatabaseId;
673         shared_msg.m_databaseid = InvalidOid;
674         regular_msg.m_nentries = 0;
675         shared_msg.m_nentries = 0;
676
677         for (tsa = pgStatTabList; tsa != NULL; tsa = tsa->tsa_next)
678         {
679                 for (i = 0; i < tsa->tsa_used; i++)
680                 {
681                         PgStat_TableStatus *entry = &tsa->tsa_entries[i];
682                         PgStat_MsgTabstat *this_msg;
683                         PgStat_TableEntry *this_ent;
684
685                         /* Shouldn't have any pending transaction-dependent counts */
686                         Assert(entry->trans == NULL);
687
688                         /*
689                          * Ignore entries that didn't accumulate any actual counts, such
690                          * as indexes that were opened by the planner but not used.
691                          */
692                         if (memcmp(&entry->t_counts, &all_zeroes,
693                                            sizeof(PgStat_TableCounts)) == 0)
694                                 continue;
695
696                         /*
697                          * OK, insert data into the appropriate message, and send if full.
698                          */
699                         this_msg = entry->t_shared ? &shared_msg : &regular_msg;
700                         this_ent = &this_msg->m_entry[this_msg->m_nentries];
701                         this_ent->t_id = entry->t_id;
702                         memcpy(&this_ent->t_counts, &entry->t_counts,
703                                    sizeof(PgStat_TableCounts));
704                         if (++this_msg->m_nentries >= PGSTAT_NUM_TABENTRIES)
705                         {
706                                 pgstat_send_tabstat(this_msg);
707                                 this_msg->m_nentries = 0;
708                         }
709                 }
710                 /* zero out TableStatus structs after use */
711                 MemSet(tsa->tsa_entries, 0,
712                            tsa->tsa_used * sizeof(PgStat_TableStatus));
713                 tsa->tsa_used = 0;
714         }
715
716         /*
717          * Send partial messages.  If force is true, make sure that any pending
718          * xact commit/abort gets counted, even if no table stats to send.
719          */
720         if (regular_msg.m_nentries > 0 ||
721                 (force && (pgStatXactCommit > 0 || pgStatXactRollback > 0)))
722                 pgstat_send_tabstat(&regular_msg);
723         if (shared_msg.m_nentries > 0)
724                 pgstat_send_tabstat(&shared_msg);
725
726         /* Now, send function statistics */
727         pgstat_send_funcstats();
728 }
729
730 /*
731  * Subroutine for pgstat_report_stat: finish and send a tabstat message
732  */
733 static void
734 pgstat_send_tabstat(PgStat_MsgTabstat *tsmsg)
735 {
736         int                     n;
737         int                     len;
738
739         /* It's unlikely we'd get here with no socket, but maybe not impossible */
740         if (pgStatSock < 0)
741                 return;
742
743         /*
744          * Report accumulated xact commit/rollback whenever we send a normal
745          * tabstat message
746          */
747         if (OidIsValid(tsmsg->m_databaseid))
748         {
749                 tsmsg->m_xact_commit = pgStatXactCommit;
750                 tsmsg->m_xact_rollback = pgStatXactRollback;
751                 pgStatXactCommit = 0;
752                 pgStatXactRollback = 0;
753         }
754         else
755         {
756                 tsmsg->m_xact_commit = 0;
757                 tsmsg->m_xact_rollback = 0;
758         }
759
760         n = tsmsg->m_nentries;
761         len = offsetof(PgStat_MsgTabstat, m_entry[0]) +
762                 n * sizeof(PgStat_TableEntry);
763
764         pgstat_setheader(&tsmsg->m_hdr, PGSTAT_MTYPE_TABSTAT);
765         pgstat_send(tsmsg, len);
766 }
767
768 /*
769  * Subroutine for pgstat_report_stat: populate and send a function stat message
770  */
771 static void
772 pgstat_send_funcstats(void)
773 {
774         /* we assume this inits to all zeroes: */
775         static const PgStat_FunctionCounts all_zeroes;
776
777         PgStat_MsgFuncstat msg;
778         PgStat_BackendFunctionEntry *entry;
779         HASH_SEQ_STATUS fstat;
780
781         if (pgStatFunctions == NULL)
782                 return;
783
784         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_FUNCSTAT);
785         msg.m_databaseid = MyDatabaseId;
786         msg.m_nentries = 0;
787
788         hash_seq_init(&fstat, pgStatFunctions);
789         while ((entry = (PgStat_BackendFunctionEntry *) hash_seq_search(&fstat)) != NULL)
790         {
791                 PgStat_FunctionEntry *m_ent;
792
793                 /* Skip it if no counts accumulated since last time */
794                 if (memcmp(&entry->f_counts, &all_zeroes,
795                                    sizeof(PgStat_FunctionCounts)) == 0)
796                         continue;
797
798                 /* need to convert format of time accumulators */
799                 m_ent = &msg.m_entry[msg.m_nentries];
800                 m_ent->f_id = entry->f_id;
801                 m_ent->f_numcalls = entry->f_counts.f_numcalls;
802                 m_ent->f_time = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_time);
803                 m_ent->f_time_self = INSTR_TIME_GET_MICROSEC(entry->f_counts.f_time_self);
804
805                 if (++msg.m_nentries >= PGSTAT_NUM_FUNCENTRIES)
806                 {
807                         pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
808                                                 msg.m_nentries * sizeof(PgStat_FunctionEntry));
809                         msg.m_nentries = 0;
810                 }
811
812                 /* reset the entry's counts */
813                 MemSet(&entry->f_counts, 0, sizeof(PgStat_FunctionCounts));
814         }
815
816         if (msg.m_nentries > 0)
817                 pgstat_send(&msg, offsetof(PgStat_MsgFuncstat, m_entry[0]) +
818                                         msg.m_nentries * sizeof(PgStat_FunctionEntry));
819 }
820
821
822 /* ----------
823  * pgstat_vacuum_stat() -
824  *
825  *      Will tell the collector about objects he can get rid of.
826  * ----------
827  */
828 void
829 pgstat_vacuum_stat(void)
830 {
831         HTAB       *htab;
832         PgStat_MsgTabpurge msg;
833         PgStat_MsgFuncpurge f_msg;
834         HASH_SEQ_STATUS hstat;
835         PgStat_StatDBEntry *dbentry;
836         PgStat_StatTabEntry *tabentry;
837         PgStat_StatFuncEntry *funcentry;
838         int                     len;
839
840         if (pgStatSock < 0)
841                 return;
842
843         /*
844          * If not done for this transaction, read the statistics collector stats
845          * file into some hash tables.
846          */
847         backend_read_statsfile();
848
849         /*
850          * Read pg_database and make a list of OIDs of all existing databases
851          */
852         htab = pgstat_collect_oids(DatabaseRelationId);
853
854         /*
855          * Search the database hash table for dead databases and tell the
856          * collector to drop them.
857          */
858         hash_seq_init(&hstat, pgStatDBHash);
859         while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
860         {
861                 Oid                     dbid = dbentry->databaseid;
862
863                 CHECK_FOR_INTERRUPTS();
864
865                 /* the DB entry for shared tables (with InvalidOid) is never dropped */
866                 if (OidIsValid(dbid) &&
867                         hash_search(htab, (void *) &dbid, HASH_FIND, NULL) == NULL)
868                         pgstat_drop_database(dbid);
869         }
870
871         /* Clean up */
872         hash_destroy(htab);
873
874         /*
875          * Lookup our own database entry; if not found, nothing more to do.
876          */
877         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
878                                                                                                  (void *) &MyDatabaseId,
879                                                                                                  HASH_FIND, NULL);
880         if (dbentry == NULL || dbentry->tables == NULL)
881                 return;
882
883         /*
884          * Similarly to above, make a list of all known relations in this DB.
885          */
886         htab = pgstat_collect_oids(RelationRelationId);
887
888         /*
889          * Initialize our messages table counter to zero
890          */
891         msg.m_nentries = 0;
892
893         /*
894          * Check for all tables listed in stats hashtable if they still exist.
895          */
896         hash_seq_init(&hstat, dbentry->tables);
897         while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&hstat)) != NULL)
898         {
899                 Oid                     tabid = tabentry->tableid;
900
901                 CHECK_FOR_INTERRUPTS();
902
903                 if (hash_search(htab, (void *) &tabid, HASH_FIND, NULL) != NULL)
904                         continue;
905
906                 /*
907                  * Not there, so add this table's Oid to the message
908                  */
909                 msg.m_tableid[msg.m_nentries++] = tabid;
910
911                 /*
912                  * If the message is full, send it out and reinitialize to empty
913                  */
914                 if (msg.m_nentries >= PGSTAT_NUM_TABPURGE)
915                 {
916                         len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
917                                 +msg.m_nentries * sizeof(Oid);
918
919                         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
920                         msg.m_databaseid = MyDatabaseId;
921                         pgstat_send(&msg, len);
922
923                         msg.m_nentries = 0;
924                 }
925         }
926
927         /*
928          * Send the rest
929          */
930         if (msg.m_nentries > 0)
931         {
932                 len = offsetof(PgStat_MsgTabpurge, m_tableid[0])
933                         +msg.m_nentries * sizeof(Oid);
934
935                 pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
936                 msg.m_databaseid = MyDatabaseId;
937                 pgstat_send(&msg, len);
938         }
939
940         /* Clean up */
941         hash_destroy(htab);
942
943         /*
944          * Now repeat the above steps for functions.
945          */
946         htab = pgstat_collect_oids(ProcedureRelationId);
947
948         pgstat_setheader(&f_msg.m_hdr, PGSTAT_MTYPE_FUNCPURGE);
949         f_msg.m_databaseid = MyDatabaseId;
950         f_msg.m_nentries = 0;
951
952         hash_seq_init(&hstat, dbentry->functions);
953         while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&hstat)) != NULL)
954         {
955                 Oid                     funcid = funcentry->functionid;
956
957                 CHECK_FOR_INTERRUPTS();
958
959                 if (hash_search(htab, (void *) &funcid, HASH_FIND, NULL) != NULL)
960                         continue;
961
962                 /*
963                  * Not there, so add this function's Oid to the message
964                  */
965                 f_msg.m_functionid[f_msg.m_nentries++] = funcid;
966
967                 /*
968                  * If the message is full, send it out and reinitialize to empty
969                  */
970                 if (f_msg.m_nentries >= PGSTAT_NUM_FUNCPURGE)
971                 {
972                         len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
973                                 +f_msg.m_nentries * sizeof(Oid);
974
975                         pgstat_send(&f_msg, len);
976
977                         f_msg.m_nentries = 0;
978                 }
979         }
980
981         /*
982          * Send the rest
983          */
984         if (f_msg.m_nentries > 0)
985         {
986                 len = offsetof(PgStat_MsgFuncpurge, m_functionid[0])
987                         +f_msg.m_nentries * sizeof(Oid);
988
989                 pgstat_send(&f_msg, len);
990         }
991
992         hash_destroy(htab);
993 }
994
995
996 /* ----------
997  * pgstat_collect_oids() -
998  *
999  *      Collect the OIDs of all objects listed in the specified system catalog
1000  *      into a temporary hash table.  Caller should hash_destroy the result
1001  *      when done with it.
1002  * ----------
1003  */
1004 static HTAB *
1005 pgstat_collect_oids(Oid catalogid)
1006 {
1007         HTAB       *htab;
1008         HASHCTL         hash_ctl;
1009         Relation        rel;
1010         HeapScanDesc scan;
1011         HeapTuple       tup;
1012
1013         memset(&hash_ctl, 0, sizeof(hash_ctl));
1014         hash_ctl.keysize = sizeof(Oid);
1015         hash_ctl.entrysize = sizeof(Oid);
1016         hash_ctl.hash = oid_hash;
1017         htab = hash_create("Temporary table of OIDs",
1018                                            PGSTAT_TAB_HASH_SIZE,
1019                                            &hash_ctl,
1020                                            HASH_ELEM | HASH_FUNCTION);
1021
1022         rel = heap_open(catalogid, AccessShareLock);
1023         scan = heap_beginscan(rel, SnapshotNow, 0, NULL);
1024         while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
1025         {
1026                 Oid                     thisoid = HeapTupleGetOid(tup);
1027
1028                 CHECK_FOR_INTERRUPTS();
1029
1030                 (void) hash_search(htab, (void *) &thisoid, HASH_ENTER, NULL);
1031         }
1032         heap_endscan(scan);
1033         heap_close(rel, AccessShareLock);
1034
1035         return htab;
1036 }
1037
1038
1039 /* ----------
1040  * pgstat_drop_database() -
1041  *
1042  *      Tell the collector that we just dropped a database.
1043  *      (If the message gets lost, we will still clean the dead DB eventually
1044  *      via future invocations of pgstat_vacuum_stat().)
1045  * ----------
1046  */
1047 void
1048 pgstat_drop_database(Oid databaseid)
1049 {
1050         PgStat_MsgDropdb msg;
1051
1052         if (pgStatSock < 0)
1053                 return;
1054
1055         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DROPDB);
1056         msg.m_databaseid = databaseid;
1057         pgstat_send(&msg, sizeof(msg));
1058 }
1059
1060
1061 /* ----------
1062  * pgstat_drop_relation() -
1063  *
1064  *      Tell the collector that we just dropped a relation.
1065  *      (If the message gets lost, we will still clean the dead entry eventually
1066  *      via future invocations of pgstat_vacuum_stat().)
1067  *
1068  *      Currently not used for lack of any good place to call it; we rely
1069  *      entirely on pgstat_vacuum_stat() to clean out stats for dead rels.
1070  * ----------
1071  */
1072 #ifdef NOT_USED
1073 void
1074 pgstat_drop_relation(Oid relid)
1075 {
1076         PgStat_MsgTabpurge msg;
1077         int                     len;
1078
1079         if (pgStatSock < 0)
1080                 return;
1081
1082         msg.m_tableid[0] = relid;
1083         msg.m_nentries = 1;
1084
1085         len = offsetof(PgStat_MsgTabpurge, m_tableid[0]) +sizeof(Oid);
1086
1087         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_TABPURGE);
1088         msg.m_databaseid = MyDatabaseId;
1089         pgstat_send(&msg, len);
1090 }
1091 #endif   /* NOT_USED */
1092
1093
1094 /* ----------
1095  * pgstat_reset_counters() -
1096  *
1097  *      Tell the statistics collector to reset counters for our database.
1098  * ----------
1099  */
1100 void
1101 pgstat_reset_counters(void)
1102 {
1103         PgStat_MsgResetcounter msg;
1104
1105         if (pgStatSock < 0)
1106                 return;
1107
1108         if (!superuser())
1109                 ereport(ERROR,
1110                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1111                                  errmsg("must be superuser to reset statistics counters")));
1112
1113         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_RESETCOUNTER);
1114         msg.m_databaseid = MyDatabaseId;
1115         pgstat_send(&msg, sizeof(msg));
1116 }
1117
1118
1119 /* ----------
1120  * pgstat_report_autovac() -
1121  *
1122  *      Called from autovacuum.c to report startup of an autovacuum process.
1123  *      We are called before InitPostgres is done, so can't rely on MyDatabaseId;
1124  *      the db OID must be passed in, instead.
1125  * ----------
1126  */
1127 void
1128 pgstat_report_autovac(Oid dboid)
1129 {
1130         PgStat_MsgAutovacStart msg;
1131
1132         if (pgStatSock < 0)
1133                 return;
1134
1135         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_AUTOVAC_START);
1136         msg.m_databaseid = dboid;
1137         msg.m_start_time = GetCurrentTimestamp();
1138
1139         pgstat_send(&msg, sizeof(msg));
1140 }
1141
1142
1143 /* ---------
1144  * pgstat_report_vacuum() -
1145  *
1146  *      Tell the collector about the table we just vacuumed.
1147  * ---------
1148  */
1149 void
1150 pgstat_report_vacuum(Oid tableoid, bool shared,
1151                                          bool analyze, PgStat_Counter tuples)
1152 {
1153         PgStat_MsgVacuum msg;
1154
1155         if (pgStatSock < 0 || !pgstat_track_counts)
1156                 return;
1157
1158         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_VACUUM);
1159         msg.m_databaseid = shared ? InvalidOid : MyDatabaseId;
1160         msg.m_tableoid = tableoid;
1161         msg.m_analyze = analyze;
1162         msg.m_autovacuum = IsAutoVacuumWorkerProcess();         /* is this autovacuum? */
1163         msg.m_vacuumtime = GetCurrentTimestamp();
1164         msg.m_tuples = tuples;
1165         pgstat_send(&msg, sizeof(msg));
1166 }
1167
1168 /* --------
1169  * pgstat_report_analyze() -
1170  *
1171  *      Tell the collector about the table we just analyzed.
1172  * --------
1173  */
1174 void
1175 pgstat_report_analyze(Relation rel, PgStat_Counter livetuples,
1176                                           PgStat_Counter deadtuples)
1177 {
1178         PgStat_MsgAnalyze msg;
1179
1180         if (pgStatSock < 0 || !pgstat_track_counts)
1181                 return;
1182
1183         /*
1184          * Unlike VACUUM, ANALYZE might be running inside a transaction that
1185          * has already inserted and/or deleted rows in the target table.
1186          * ANALYZE will have counted such rows as live or dead respectively.
1187          * Because we will report our counts of such rows at transaction end,
1188          * we should subtract off these counts from what we send to the collector
1189          * now, else they'll be double-counted after commit.  (This approach also
1190          * ensures that the collector ends up with the right numbers if we abort
1191          * instead of committing.)
1192          */
1193         if (rel->pgstat_info != NULL)
1194         {
1195                 PgStat_TableXactStatus *trans;
1196
1197                 for (trans = rel->pgstat_info->trans; trans; trans = trans->upper)
1198                 {
1199                         livetuples -= trans->tuples_inserted - trans->tuples_deleted;
1200                         deadtuples -= trans->tuples_deleted;
1201                 }
1202                 /* count stuff inserted by already-aborted subxacts, too */
1203                 deadtuples -= rel->pgstat_info->t_counts.t_new_dead_tuples;
1204                 /* Since ANALYZE's counts are estimates, we could have underflowed */
1205                 livetuples = Max(livetuples, 0);
1206                 deadtuples = Max(deadtuples, 0);
1207         }
1208
1209         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_ANALYZE);
1210         msg.m_databaseid = rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId;
1211         msg.m_tableoid = RelationGetRelid(rel);
1212         msg.m_autovacuum = IsAutoVacuumWorkerProcess(); /* is this autovacuum? */
1213         msg.m_analyzetime = GetCurrentTimestamp();
1214         msg.m_live_tuples = livetuples;
1215         msg.m_dead_tuples = deadtuples;
1216         pgstat_send(&msg, sizeof(msg));
1217 }
1218
1219
1220 /* ----------
1221  * pgstat_ping() -
1222  *
1223  *      Send some junk data to the collector to increase traffic.
1224  * ----------
1225  */
1226 void
1227 pgstat_ping(void)
1228 {
1229         PgStat_MsgDummy msg;
1230
1231         if (pgStatSock < 0)
1232                 return;
1233
1234         pgstat_setheader(&msg.m_hdr, PGSTAT_MTYPE_DUMMY);
1235         pgstat_send(&msg, sizeof(msg));
1236 }
1237
1238 /*
1239  * Initialize function call usage data.
1240  * Called by the executor before invoking a function.
1241  */
1242 void
1243 pgstat_init_function_usage(FunctionCallInfoData *fcinfo,
1244                                                    PgStat_FunctionCallUsage *fcu)
1245 {
1246         PgStat_BackendFunctionEntry *htabent;
1247         bool            found;
1248
1249         if (pgstat_track_functions <= fcinfo->flinfo->fn_stats)
1250         {
1251                 /* stats not wanted */
1252                 fcu->fs = NULL;
1253                 return;
1254         }
1255
1256         if (!pgStatFunctions)
1257         {
1258                 /* First time through - initialize function stat table */
1259                 HASHCTL         hash_ctl;
1260
1261                 memset(&hash_ctl, 0, sizeof(hash_ctl));
1262                 hash_ctl.keysize = sizeof(Oid);
1263                 hash_ctl.entrysize = sizeof(PgStat_BackendFunctionEntry);
1264                 hash_ctl.hash = oid_hash;
1265                 pgStatFunctions = hash_create("Function stat entries",
1266                                                                           PGSTAT_FUNCTION_HASH_SIZE,
1267                                                                           &hash_ctl,
1268                                                                           HASH_ELEM | HASH_FUNCTION);
1269         }
1270
1271         /* Get the stats entry for this function, create if necessary */
1272         htabent = hash_search(pgStatFunctions, &fcinfo->flinfo->fn_oid,
1273                                                   HASH_ENTER, &found);
1274         if (!found)
1275                 MemSet(&htabent->f_counts, 0, sizeof(PgStat_FunctionCounts));
1276
1277         fcu->fs = &htabent->f_counts;
1278
1279         /* save stats for this function, later used to compensate for recursion */
1280         fcu->save_f_time = htabent->f_counts.f_time;
1281
1282         /* save current backend-wide total time */
1283         fcu->save_total = total_func_time;
1284
1285         /* get clock time as of function start */
1286         INSTR_TIME_SET_CURRENT(fcu->f_start);
1287 }
1288
1289 /*
1290  * Calculate function call usage and update stat counters.
1291  * Called by the executor after invoking a function.
1292  *
1293  * In the case of a set-returning function that runs in value-per-call mode,
1294  * we will see multiple pgstat_init_function_usage/pgstat_end_function_usage
1295  * calls for what the user considers a single call of the function.  The
1296  * finalize flag should be TRUE on the last call.
1297  */
1298 void
1299 pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
1300 {
1301         PgStat_FunctionCounts *fs = fcu->fs;
1302         instr_time      f_total;
1303         instr_time      f_others;
1304         instr_time      f_self;
1305
1306         /* stats not wanted? */
1307         if (fs == NULL)
1308                 return;
1309
1310         /* total elapsed time in this function call */
1311         INSTR_TIME_SET_CURRENT(f_total);
1312         INSTR_TIME_SUBTRACT(f_total, fcu->f_start);
1313
1314         /* self usage: elapsed minus anything already charged to other calls */
1315         f_others = total_func_time;
1316         INSTR_TIME_SUBTRACT(f_others, fcu->save_total);
1317         f_self = f_total;
1318         INSTR_TIME_SUBTRACT(f_self, f_others);
1319
1320         /* update backend-wide total time */
1321         INSTR_TIME_ADD(total_func_time, f_self);
1322
1323         /*
1324          * Compute the new total f_time as the total elapsed time added to the
1325          * pre-call value of f_time.  This is necessary to avoid double-counting
1326          * any time taken by recursive calls of myself.  (We do not need any
1327          * similar kluge for self time, since that already excludes any
1328          * recursive calls.)
1329          */
1330         INSTR_TIME_ADD(f_total, fcu->save_f_time);
1331
1332         /* update counters in function stats table */
1333         if (finalize)
1334                 fs->f_numcalls++;
1335         fs->f_time = f_total;
1336         INSTR_TIME_ADD(fs->f_time_self, f_self);
1337 }
1338
1339
1340 /* ----------
1341  * pgstat_initstats() -
1342  *
1343  *      Initialize a relcache entry to count access statistics.
1344  *      Called whenever a relation is opened.
1345  *
1346  *      We assume that a relcache entry's pgstat_info field is zeroed by
1347  *      relcache.c when the relcache entry is made; thereafter it is long-lived
1348  *      data.  We can avoid repeated searches of the TabStatus arrays when the
1349  *      same relation is touched repeatedly within a transaction.
1350  * ----------
1351  */
1352 void
1353 pgstat_initstats(Relation rel)
1354 {
1355         Oid                     rel_id = rel->rd_id;
1356         char            relkind = rel->rd_rel->relkind;
1357
1358         /* We only count stats for things that have storage */
1359         if (!(relkind == RELKIND_RELATION ||
1360                   relkind == RELKIND_INDEX ||
1361                   relkind == RELKIND_TOASTVALUE))
1362         {
1363                 rel->pgstat_info = NULL;
1364                 return;
1365         }
1366
1367         if (pgStatSock < 0 || !pgstat_track_counts)
1368         {
1369                 /* We're not counting at all */
1370                 rel->pgstat_info = NULL;
1371                 return;
1372         }
1373
1374         /*
1375          * If we already set up this relation in the current transaction, nothing
1376          * to do.
1377          */
1378         if (rel->pgstat_info != NULL &&
1379                 rel->pgstat_info->t_id == rel_id)
1380                 return;
1381
1382         /* Else find or make the PgStat_TableStatus entry, and update link */
1383         rel->pgstat_info = get_tabstat_entry(rel_id, rel->rd_rel->relisshared);
1384 }
1385
1386 /*
1387  * get_tabstat_entry - find or create a PgStat_TableStatus entry for rel
1388  */
1389 static PgStat_TableStatus *
1390 get_tabstat_entry(Oid rel_id, bool isshared)
1391 {
1392         PgStat_TableStatus *entry;
1393         TabStatusArray *tsa;
1394         TabStatusArray *prev_tsa;
1395         int                     i;
1396
1397         /*
1398          * Search the already-used tabstat slots for this relation.
1399          */
1400         prev_tsa = NULL;
1401         for (tsa = pgStatTabList; tsa != NULL; prev_tsa = tsa, tsa = tsa->tsa_next)
1402         {
1403                 for (i = 0; i < tsa->tsa_used; i++)
1404                 {
1405                         entry = &tsa->tsa_entries[i];
1406                         if (entry->t_id == rel_id)
1407                                 return entry;
1408                 }
1409
1410                 if (tsa->tsa_used < TABSTAT_QUANTUM)
1411                 {
1412                         /*
1413                          * It must not be present, but we found a free slot instead. Fine,
1414                          * let's use this one.  We assume the entry was already zeroed,
1415                          * either at creation or after last use.
1416                          */
1417                         entry = &tsa->tsa_entries[tsa->tsa_used++];
1418                         entry->t_id = rel_id;
1419                         entry->t_shared = isshared;
1420                         return entry;
1421                 }
1422         }
1423
1424         /*
1425          * We ran out of tabstat slots, so allocate more.  Be sure they're zeroed.
1426          */
1427         tsa = (TabStatusArray *) MemoryContextAllocZero(TopMemoryContext,
1428                                                                                                         sizeof(TabStatusArray));
1429         if (prev_tsa)
1430                 prev_tsa->tsa_next = tsa;
1431         else
1432                 pgStatTabList = tsa;
1433
1434         /*
1435          * Use the first entry of the new TabStatusArray.
1436          */
1437         entry = &tsa->tsa_entries[tsa->tsa_used++];
1438         entry->t_id = rel_id;
1439         entry->t_shared = isshared;
1440         return entry;
1441 }
1442
1443 /*
1444  * get_tabstat_stack_level - add a new (sub)transaction stack entry if needed
1445  */
1446 static PgStat_SubXactStatus *
1447 get_tabstat_stack_level(int nest_level)
1448 {
1449         PgStat_SubXactStatus *xact_state;
1450
1451         xact_state = pgStatXactStack;
1452         if (xact_state == NULL || xact_state->nest_level != nest_level)
1453         {
1454                 xact_state = (PgStat_SubXactStatus *)
1455                         MemoryContextAlloc(TopTransactionContext,
1456                                                            sizeof(PgStat_SubXactStatus));
1457                 xact_state->nest_level = nest_level;
1458                 xact_state->prev = pgStatXactStack;
1459                 xact_state->first = NULL;
1460                 pgStatXactStack = xact_state;
1461         }
1462         return xact_state;
1463 }
1464
1465 /*
1466  * add_tabstat_xact_level - add a new (sub)transaction state record
1467  */
1468 static void
1469 add_tabstat_xact_level(PgStat_TableStatus *pgstat_info, int nest_level)
1470 {
1471         PgStat_SubXactStatus *xact_state;
1472         PgStat_TableXactStatus *trans;
1473
1474         /*
1475          * If this is the first rel to be modified at the current nest level, we
1476          * first have to push a transaction stack entry.
1477          */
1478         xact_state = get_tabstat_stack_level(nest_level);
1479
1480         /* Now make a per-table stack entry */
1481         trans = (PgStat_TableXactStatus *)
1482                 MemoryContextAllocZero(TopTransactionContext,
1483                                                            sizeof(PgStat_TableXactStatus));
1484         trans->nest_level = nest_level;
1485         trans->upper = pgstat_info->trans;
1486         trans->parent = pgstat_info;
1487         trans->next = xact_state->first;
1488         xact_state->first = trans;
1489         pgstat_info->trans = trans;
1490 }
1491
1492 /*
1493  * pgstat_count_heap_insert - count a tuple insertion
1494  */
1495 void
1496 pgstat_count_heap_insert(Relation rel)
1497 {
1498         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1499
1500         if (pgstat_track_counts && pgstat_info != NULL)
1501         {
1502                 int                     nest_level = GetCurrentTransactionNestLevel();
1503
1504                 /* t_tuples_inserted is nontransactional, so just advance it */
1505                 pgstat_info->t_counts.t_tuples_inserted++;
1506
1507                 /* We have to log the transactional effect at the proper level */
1508                 if (pgstat_info->trans == NULL ||
1509                         pgstat_info->trans->nest_level != nest_level)
1510                         add_tabstat_xact_level(pgstat_info, nest_level);
1511
1512                 pgstat_info->trans->tuples_inserted++;
1513         }
1514 }
1515
1516 /*
1517  * pgstat_count_heap_update - count a tuple update
1518  */
1519 void
1520 pgstat_count_heap_update(Relation rel, bool hot)
1521 {
1522         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1523
1524         if (pgstat_track_counts && pgstat_info != NULL)
1525         {
1526                 int                     nest_level = GetCurrentTransactionNestLevel();
1527
1528                 /* t_tuples_updated is nontransactional, so just advance it */
1529                 pgstat_info->t_counts.t_tuples_updated++;
1530                 /* ditto for the hot_update counter */
1531                 if (hot)
1532                         pgstat_info->t_counts.t_tuples_hot_updated++;
1533
1534                 /* We have to log the transactional effect at the proper level */
1535                 if (pgstat_info->trans == NULL ||
1536                         pgstat_info->trans->nest_level != nest_level)
1537                         add_tabstat_xact_level(pgstat_info, nest_level);
1538
1539                 /* An UPDATE both inserts a new tuple and deletes the old */
1540                 pgstat_info->trans->tuples_inserted++;
1541                 pgstat_info->trans->tuples_deleted++;
1542         }
1543 }
1544
1545 /*
1546  * pgstat_count_heap_delete - count a tuple deletion
1547  */
1548 void
1549 pgstat_count_heap_delete(Relation rel)
1550 {
1551         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1552
1553         if (pgstat_track_counts && pgstat_info != NULL)
1554         {
1555                 int                     nest_level = GetCurrentTransactionNestLevel();
1556
1557                 /* t_tuples_deleted is nontransactional, so just advance it */
1558                 pgstat_info->t_counts.t_tuples_deleted++;
1559
1560                 /* We have to log the transactional effect at the proper level */
1561                 if (pgstat_info->trans == NULL ||
1562                         pgstat_info->trans->nest_level != nest_level)
1563                         add_tabstat_xact_level(pgstat_info, nest_level);
1564
1565                 pgstat_info->trans->tuples_deleted++;
1566         }
1567 }
1568
1569 /*
1570  * pgstat_update_heap_dead_tuples - update dead-tuples count
1571  *
1572  * The semantics of this are that we are reporting the nontransactional
1573  * recovery of "delta" dead tuples; so t_new_dead_tuples decreases
1574  * rather than increasing, and the change goes straight into the per-table
1575  * counter, not into transactional state.
1576  */
1577 void
1578 pgstat_update_heap_dead_tuples(Relation rel, int delta)
1579 {
1580         PgStat_TableStatus *pgstat_info = rel->pgstat_info;
1581
1582         if (pgstat_track_counts && pgstat_info != NULL)
1583                 pgstat_info->t_counts.t_new_dead_tuples -= delta;
1584 }
1585
1586
1587 /* ----------
1588  * AtEOXact_PgStat
1589  *
1590  *      Called from access/transam/xact.c at top-level transaction commit/abort.
1591  * ----------
1592  */
1593 void
1594 AtEOXact_PgStat(bool isCommit)
1595 {
1596         PgStat_SubXactStatus *xact_state;
1597
1598         /*
1599          * Count transaction commit or abort.  (We use counters, not just bools,
1600          * in case the reporting message isn't sent right away.)
1601          */
1602         if (isCommit)
1603                 pgStatXactCommit++;
1604         else
1605                 pgStatXactRollback++;
1606
1607         /*
1608          * Transfer transactional insert/update counts into the base tabstat
1609          * entries.  We don't bother to free any of the transactional state, since
1610          * it's all in TopTransactionContext and will go away anyway.
1611          */
1612         xact_state = pgStatXactStack;
1613         if (xact_state != NULL)
1614         {
1615                 PgStat_TableXactStatus *trans;
1616
1617                 Assert(xact_state->nest_level == 1);
1618                 Assert(xact_state->prev == NULL);
1619                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1620                 {
1621                         PgStat_TableStatus *tabstat;
1622
1623                         Assert(trans->nest_level == 1);
1624                         Assert(trans->upper == NULL);
1625                         tabstat = trans->parent;
1626                         Assert(tabstat->trans == trans);
1627                         if (isCommit)
1628                         {
1629                                 tabstat->t_counts.t_new_live_tuples +=
1630                                         trans->tuples_inserted - trans->tuples_deleted;
1631                                 tabstat->t_counts.t_new_dead_tuples += trans->tuples_deleted;
1632                         }
1633                         else
1634                         {
1635                                 /* inserted tuples are dead, deleted tuples are unaffected */
1636                                 tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
1637                         }
1638                         tabstat->trans = NULL;
1639                 }
1640         }
1641         pgStatXactStack = NULL;
1642
1643         /* Make sure any stats snapshot is thrown away */
1644         pgstat_clear_snapshot();
1645 }
1646
1647 /* ----------
1648  * AtEOSubXact_PgStat
1649  *
1650  *      Called from access/transam/xact.c at subtransaction commit/abort.
1651  * ----------
1652  */
1653 void
1654 AtEOSubXact_PgStat(bool isCommit, int nestDepth)
1655 {
1656         PgStat_SubXactStatus *xact_state;
1657
1658         /*
1659          * Transfer transactional insert/update counts into the next higher
1660          * subtransaction state.
1661          */
1662         xact_state = pgStatXactStack;
1663         if (xact_state != NULL &&
1664                 xact_state->nest_level >= nestDepth)
1665         {
1666                 PgStat_TableXactStatus *trans;
1667                 PgStat_TableXactStatus *next_trans;
1668
1669                 /* delink xact_state from stack immediately to simplify reuse case */
1670                 pgStatXactStack = xact_state->prev;
1671
1672                 for (trans = xact_state->first; trans != NULL; trans = next_trans)
1673                 {
1674                         PgStat_TableStatus *tabstat;
1675
1676                         next_trans = trans->next;
1677                         Assert(trans->nest_level == nestDepth);
1678                         tabstat = trans->parent;
1679                         Assert(tabstat->trans == trans);
1680                         if (isCommit)
1681                         {
1682                                 if (trans->upper && trans->upper->nest_level == nestDepth - 1)
1683                                 {
1684                                         trans->upper->tuples_inserted += trans->tuples_inserted;
1685                                         trans->upper->tuples_deleted += trans->tuples_deleted;
1686                                         tabstat->trans = trans->upper;
1687                                         pfree(trans);
1688                                 }
1689                                 else
1690                                 {
1691                                         /*
1692                                          * When there isn't an immediate parent state, we can just
1693                                          * reuse the record instead of going through a
1694                                          * palloc/pfree pushup (this works since it's all in
1695                                          * TopTransactionContext anyway).  We have to re-link it
1696                                          * into the parent level, though, and that might mean
1697                                          * pushing a new entry into the pgStatXactStack.
1698                                          */
1699                                         PgStat_SubXactStatus *upper_xact_state;
1700
1701                                         upper_xact_state = get_tabstat_stack_level(nestDepth - 1);
1702                                         trans->next = upper_xact_state->first;
1703                                         upper_xact_state->first = trans;
1704                                         trans->nest_level = nestDepth - 1;
1705                                 }
1706                         }
1707                         else
1708                         {
1709                                 /*
1710                                  * On abort, inserted tuples are dead (and can be bounced out
1711                                  * to the top-level tabstat), deleted tuples are unaffected
1712                                  */
1713                                 tabstat->t_counts.t_new_dead_tuples += trans->tuples_inserted;
1714                                 tabstat->trans = trans->upper;
1715                                 pfree(trans);
1716                         }
1717                 }
1718                 pfree(xact_state);
1719         }
1720 }
1721
1722
1723 /*
1724  * AtPrepare_PgStat
1725  *              Save the transactional stats state at 2PC transaction prepare.
1726  *
1727  * In this phase we just generate 2PC records for all the pending
1728  * transaction-dependent stats work.
1729  */
1730 void
1731 AtPrepare_PgStat(void)
1732 {
1733         PgStat_SubXactStatus *xact_state;
1734
1735         xact_state = pgStatXactStack;
1736         if (xact_state != NULL)
1737         {
1738                 PgStat_TableXactStatus *trans;
1739
1740                 Assert(xact_state->nest_level == 1);
1741                 Assert(xact_state->prev == NULL);
1742                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1743                 {
1744                         PgStat_TableStatus *tabstat;
1745                         TwoPhasePgStatRecord record;
1746
1747                         Assert(trans->nest_level == 1);
1748                         Assert(trans->upper == NULL);
1749                         tabstat = trans->parent;
1750                         Assert(tabstat->trans == trans);
1751
1752                         record.tuples_inserted = trans->tuples_inserted;
1753                         record.tuples_deleted = trans->tuples_deleted;
1754                         record.t_id = tabstat->t_id;
1755                         record.t_shared = tabstat->t_shared;
1756
1757                         RegisterTwoPhaseRecord(TWOPHASE_RM_PGSTAT_ID, 0,
1758                                                                    &record, sizeof(TwoPhasePgStatRecord));
1759                 }
1760         }
1761 }
1762
1763 /*
1764  * PostPrepare_PgStat
1765  *              Clean up after successful PREPARE.
1766  *
1767  * All we need do here is unlink the transaction stats state from the
1768  * nontransactional state.      The nontransactional action counts will be
1769  * reported to the stats collector immediately, while the effects on live
1770  * and dead tuple counts are preserved in the 2PC state file.
1771  *
1772  * Note: AtEOXact_PgStat is not called during PREPARE.
1773  */
1774 void
1775 PostPrepare_PgStat(void)
1776 {
1777         PgStat_SubXactStatus *xact_state;
1778
1779         /*
1780          * We don't bother to free any of the transactional state, since it's all
1781          * in TopTransactionContext and will go away anyway.
1782          */
1783         xact_state = pgStatXactStack;
1784         if (xact_state != NULL)
1785         {
1786                 PgStat_TableXactStatus *trans;
1787
1788                 for (trans = xact_state->first; trans != NULL; trans = trans->next)
1789                 {
1790                         PgStat_TableStatus *tabstat;
1791
1792                         tabstat = trans->parent;
1793                         tabstat->trans = NULL;
1794                 }
1795         }
1796         pgStatXactStack = NULL;
1797
1798         /* Make sure any stats snapshot is thrown away */
1799         pgstat_clear_snapshot();
1800 }
1801
1802 /*
1803  * 2PC processing routine for COMMIT PREPARED case.
1804  *
1805  * Load the saved counts into our local pgstats state.
1806  */
1807 void
1808 pgstat_twophase_postcommit(TransactionId xid, uint16 info,
1809                                                    void *recdata, uint32 len)
1810 {
1811         TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
1812         PgStat_TableStatus *pgstat_info;
1813
1814         /* Find or create a tabstat entry for the rel */
1815         pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
1816
1817         pgstat_info->t_counts.t_new_live_tuples +=
1818                 rec->tuples_inserted - rec->tuples_deleted;
1819         pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_deleted;
1820 }
1821
1822 /*
1823  * 2PC processing routine for ROLLBACK PREPARED case.
1824  *
1825  * Load the saved counts into our local pgstats state, but treat them
1826  * as aborted.
1827  */
1828 void
1829 pgstat_twophase_postabort(TransactionId xid, uint16 info,
1830                                                   void *recdata, uint32 len)
1831 {
1832         TwoPhasePgStatRecord *rec = (TwoPhasePgStatRecord *) recdata;
1833         PgStat_TableStatus *pgstat_info;
1834
1835         /* Find or create a tabstat entry for the rel */
1836         pgstat_info = get_tabstat_entry(rec->t_id, rec->t_shared);
1837
1838         /* inserted tuples are dead, deleted tuples are no-ops */
1839         pgstat_info->t_counts.t_new_dead_tuples += rec->tuples_inserted;
1840 }
1841
1842
1843 /* ----------
1844  * pgstat_fetch_stat_dbentry() -
1845  *
1846  *      Support function for the SQL-callable pgstat* functions. Returns
1847  *      the collected statistics for one database or NULL. NULL doesn't mean
1848  *      that the database doesn't exist, it is just not yet known by the
1849  *      collector, so the caller is better off to report ZERO instead.
1850  * ----------
1851  */
1852 PgStat_StatDBEntry *
1853 pgstat_fetch_stat_dbentry(Oid dbid)
1854 {
1855         /*
1856          * If not done for this transaction, read the statistics collector stats
1857          * file into some hash tables.
1858          */
1859         backend_read_statsfile();
1860
1861         /*
1862          * Lookup the requested database; return NULL if not found
1863          */
1864         return (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1865                                                                                           (void *) &dbid,
1866                                                                                           HASH_FIND, NULL);
1867 }
1868
1869
1870 /* ----------
1871  * pgstat_fetch_stat_tabentry() -
1872  *
1873  *      Support function for the SQL-callable pgstat* functions. Returns
1874  *      the collected statistics for one table or NULL. NULL doesn't mean
1875  *      that the table doesn't exist, it is just not yet known by the
1876  *      collector, so the caller is better off to report ZERO instead.
1877  * ----------
1878  */
1879 PgStat_StatTabEntry *
1880 pgstat_fetch_stat_tabentry(Oid relid)
1881 {
1882         Oid                     dbid;
1883         PgStat_StatDBEntry *dbentry;
1884         PgStat_StatTabEntry *tabentry;
1885
1886         /*
1887          * If not done for this transaction, read the statistics collector stats
1888          * file into some hash tables.
1889          */
1890         backend_read_statsfile();
1891
1892         /*
1893          * Lookup our database, then look in its table hash table.
1894          */
1895         dbid = MyDatabaseId;
1896         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1897                                                                                                  (void *) &dbid,
1898                                                                                                  HASH_FIND, NULL);
1899         if (dbentry != NULL && dbentry->tables != NULL)
1900         {
1901                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1902                                                                                                            (void *) &relid,
1903                                                                                                            HASH_FIND, NULL);
1904                 if (tabentry)
1905                         return tabentry;
1906         }
1907
1908         /*
1909          * If we didn't find it, maybe it's a shared table.
1910          */
1911         dbid = InvalidOid;
1912         dbentry = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
1913                                                                                                  (void *) &dbid,
1914                                                                                                  HASH_FIND, NULL);
1915         if (dbentry != NULL && dbentry->tables != NULL)
1916         {
1917                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
1918                                                                                                            (void *) &relid,
1919                                                                                                            HASH_FIND, NULL);
1920                 if (tabentry)
1921                         return tabentry;
1922         }
1923
1924         return NULL;
1925 }
1926
1927
1928 /* ----------
1929  * pgstat_fetch_stat_funcentry() -
1930  *
1931  *      Support function for the SQL-callable pgstat* functions. Returns
1932  *      the collected statistics for one function or NULL.
1933  * ----------
1934  */
1935 PgStat_StatFuncEntry *
1936 pgstat_fetch_stat_funcentry(Oid func_id)
1937 {
1938         PgStat_StatDBEntry *dbentry;
1939         PgStat_StatFuncEntry *funcentry = NULL;
1940
1941         /* load the stats file if needed */
1942         backend_read_statsfile();
1943
1944         /* Lookup our database, then find the requested function.  */
1945         dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
1946         if (dbentry != NULL && dbentry->functions != NULL)
1947         {
1948                 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
1949                                                                                                                  (void *) &func_id,
1950                                                                                                                  HASH_FIND, NULL);
1951         }
1952
1953         return funcentry;
1954 }
1955
1956
1957 /* ----------
1958  * pgstat_fetch_stat_beentry() -
1959  *
1960  *      Support function for the SQL-callable pgstat* functions. Returns
1961  *      our local copy of the current-activity entry for one backend.
1962  *
1963  *      NB: caller is responsible for a check if the user is permitted to see
1964  *      this info (especially the querystring).
1965  * ----------
1966  */
1967 PgBackendStatus *
1968 pgstat_fetch_stat_beentry(int beid)
1969 {
1970         pgstat_read_current_status();
1971
1972         if (beid < 1 || beid > localNumBackends)
1973                 return NULL;
1974
1975         return &localBackendStatusTable[beid - 1];
1976 }
1977
1978
1979 /* ----------
1980  * pgstat_fetch_stat_numbackends() -
1981  *
1982  *      Support function for the SQL-callable pgstat* functions. Returns
1983  *      the maximum current backend id.
1984  * ----------
1985  */
1986 int
1987 pgstat_fetch_stat_numbackends(void)
1988 {
1989         pgstat_read_current_status();
1990
1991         return localNumBackends;
1992 }
1993
1994 /*
1995  * ---------
1996  * pgstat_fetch_global() -
1997  *
1998  *      Support function for the SQL-callable pgstat* functions. Returns
1999  *      a pointer to the global statistics struct.
2000  * ---------
2001  */
2002 PgStat_GlobalStats *
2003 pgstat_fetch_global(void)
2004 {
2005         backend_read_statsfile();
2006
2007         return &globalStats;
2008 }
2009
2010
2011 /* ------------------------------------------------------------
2012  * Functions for management of the shared-memory PgBackendStatus array
2013  * ------------------------------------------------------------
2014  */
2015
2016 static PgBackendStatus *BackendStatusArray = NULL;
2017 static PgBackendStatus *MyBEEntry = NULL;
2018 static char                        *BackendActivityBuffer = NULL;
2019
2020
2021 /*
2022  * Report shared-memory space needed by CreateSharedBackendStatus.
2023  */
2024 Size
2025 BackendStatusShmemSize(void)
2026 {
2027         Size            size;
2028
2029         size = add_size(mul_size(sizeof(PgBackendStatus), MaxBackends),
2030                                         mul_size(pgstat_track_activity_query_size, MaxBackends));
2031         return size;
2032 }
2033
2034 /*
2035  * Initialize the shared status array and activity string buffer during
2036  * postmaster startup.
2037  */
2038 void
2039 CreateSharedBackendStatus(void)
2040 {
2041         Size            size;
2042         bool            found;
2043         int                     i;
2044         char       *buffer;
2045
2046         /* Create or attach to the shared array */
2047         size = mul_size(sizeof(PgBackendStatus), MaxBackends);
2048         BackendStatusArray = (PgBackendStatus *)
2049                 ShmemInitStruct("Backend Status Array", size, &found);
2050
2051         if (!found)
2052         {
2053                 /*
2054                  * We're the first - initialize.
2055                  */
2056                 MemSet(BackendStatusArray, 0, size);
2057         }
2058
2059         /* Create or attach to the shared activity buffer */
2060         size = mul_size(pgstat_track_activity_query_size, MaxBackends);
2061         BackendActivityBuffer = (char*)
2062                 ShmemInitStruct("Backend Activity Buffer", size, &found);
2063
2064         if (!found)
2065         {
2066                 MemSet(BackendActivityBuffer, 0, size);
2067
2068                 /* Initialize st_activity pointers. */
2069                 buffer = BackendActivityBuffer;
2070                 for (i = 0; i < MaxBackends; i++) {
2071                         BackendStatusArray[i].st_activity = buffer;
2072                         buffer += pgstat_track_activity_query_size;
2073                 }
2074         }
2075 }
2076
2077
2078 /* ----------
2079  * pgstat_initialize() -
2080  *
2081  *      Initialize pgstats state, and set up our on-proc-exit hook.
2082  *      Called from InitPostgres.  MyBackendId must be set,
2083  *      but we must not have started any transaction yet (since the
2084  *      exit hook must run after the last transaction exit).
2085  * ----------
2086  */
2087 void
2088 pgstat_initialize(void)
2089 {
2090         /* Initialize MyBEEntry */
2091         Assert(MyBackendId >= 1 && MyBackendId <= MaxBackends);
2092         MyBEEntry = &BackendStatusArray[MyBackendId - 1];
2093
2094         /* Set up a process-exit hook to clean up */
2095         on_shmem_exit(pgstat_beshutdown_hook, 0);
2096 }
2097
2098 /* ----------
2099  * pgstat_bestart() -
2100  *
2101  *      Initialize this backend's entry in the PgBackendStatus array.
2102  *      Called from InitPostgres.  MyDatabaseId and session userid must be set
2103  *      (hence, this cannot be combined with pgstat_initialize).
2104  * ----------
2105  */
2106 void
2107 pgstat_bestart(void)
2108 {
2109         TimestampTz proc_start_timestamp;
2110         Oid                     userid;
2111         SockAddr        clientaddr;
2112         volatile PgBackendStatus *beentry;
2113
2114         /*
2115          * To minimize the time spent modifying the PgBackendStatus entry, fetch
2116          * all the needed data first.
2117          *
2118          * If we have a MyProcPort, use its session start time (for consistency,
2119          * and to save a kernel call).
2120          */
2121         if (MyProcPort)
2122                 proc_start_timestamp = MyProcPort->SessionStartTime;
2123         else
2124                 proc_start_timestamp = GetCurrentTimestamp();
2125         userid = GetSessionUserId();
2126
2127         /*
2128          * We may not have a MyProcPort (eg, if this is the autovacuum process).
2129          * If so, use all-zeroes client address, which is dealt with specially in
2130          * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
2131          */
2132         if (MyProcPort)
2133                 memcpy(&clientaddr, &MyProcPort->raddr, sizeof(clientaddr));
2134         else
2135                 MemSet(&clientaddr, 0, sizeof(clientaddr));
2136
2137         /*
2138          * Initialize my status entry, following the protocol of bumping
2139          * st_changecount before and after; and make sure it's even afterwards. We
2140          * use a volatile pointer here to ensure the compiler doesn't try to get
2141          * cute.
2142          */
2143         beentry = MyBEEntry;
2144         do
2145         {
2146                 beentry->st_changecount++;
2147         } while ((beentry->st_changecount & 1) == 0);
2148
2149         beentry->st_procpid = MyProcPid;
2150         beentry->st_proc_start_timestamp = proc_start_timestamp;
2151         beentry->st_activity_start_timestamp = 0;
2152         beentry->st_xact_start_timestamp = 0;
2153         beentry->st_databaseid = MyDatabaseId;
2154         beentry->st_userid = userid;
2155         beentry->st_clientaddr = clientaddr;
2156         beentry->st_waiting = false;
2157         beentry->st_activity[0] = '\0';
2158         /* Also make sure the last byte in the string area is always 0 */
2159         beentry->st_activity[pgstat_track_activity_query_size - 1] = '\0';
2160
2161         beentry->st_changecount++;
2162         Assert((beentry->st_changecount & 1) == 0);
2163 }
2164
2165 /*
2166  * Shut down a single backend's statistics reporting at process exit.
2167  *
2168  * Flush any remaining statistics counts out to the collector.
2169  * Without this, operations triggered during backend exit (such as
2170  * temp table deletions) won't be counted.
2171  *
2172  * Lastly, clear out our entry in the PgBackendStatus array.
2173  */
2174 static void
2175 pgstat_beshutdown_hook(int code, Datum arg)
2176 {
2177         volatile PgBackendStatus *beentry = MyBEEntry;
2178
2179         pgstat_report_stat(true);
2180
2181         /*
2182          * Clear my status entry, following the protocol of bumping st_changecount
2183          * before and after.  We use a volatile pointer here to ensure the
2184          * compiler doesn't try to get cute.
2185          */
2186         beentry->st_changecount++;
2187
2188         beentry->st_procpid = 0;        /* mark invalid */
2189
2190         beentry->st_changecount++;
2191         Assert((beentry->st_changecount & 1) == 0);
2192 }
2193
2194
2195 /* ----------
2196  * pgstat_report_activity() -
2197  *
2198  *      Called from tcop/postgres.c to report what the backend is actually doing
2199  *      (usually "<IDLE>" or the start of the query to be executed).
2200  * ----------
2201  */
2202 void
2203 pgstat_report_activity(const char *cmd_str)
2204 {
2205         volatile PgBackendStatus *beentry = MyBEEntry;
2206         TimestampTz start_timestamp;
2207         int                     len;
2208
2209         TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
2210
2211         if (!pgstat_track_activities || !beentry)
2212                 return;
2213
2214         /*
2215          * To minimize the time spent modifying the entry, fetch all the needed
2216          * data first.
2217          */
2218         start_timestamp = GetCurrentStatementStartTimestamp();
2219
2220         len = strlen(cmd_str);
2221         len = pg_mbcliplen(cmd_str, len, pgstat_track_activity_query_size - 1);
2222
2223         /*
2224          * Update my status entry, following the protocol of bumping
2225          * st_changecount before and after.  We use a volatile pointer here to
2226          * ensure the compiler doesn't try to get cute.
2227          */
2228         beentry->st_changecount++;
2229
2230         beentry->st_activity_start_timestamp = start_timestamp;
2231         memcpy((char *) beentry->st_activity, cmd_str, len);
2232         beentry->st_activity[len] = '\0';
2233
2234         beentry->st_changecount++;
2235         Assert((beentry->st_changecount & 1) == 0);
2236 }
2237
2238 /*
2239  * Report current transaction start timestamp as the specified value.
2240  * Zero means there is no active transaction.
2241  */
2242 void
2243 pgstat_report_xact_timestamp(TimestampTz tstamp)
2244 {
2245         volatile PgBackendStatus *beentry = MyBEEntry;
2246
2247         if (!pgstat_track_activities || !beentry)
2248                 return;
2249
2250         /*
2251          * Update my status entry, following the protocol of bumping
2252          * st_changecount before and after.  We use a volatile pointer here to
2253          * ensure the compiler doesn't try to get cute.
2254          */
2255         beentry->st_changecount++;
2256         beentry->st_xact_start_timestamp = tstamp;
2257         beentry->st_changecount++;
2258         Assert((beentry->st_changecount & 1) == 0);
2259 }
2260
2261 /* ----------
2262  * pgstat_report_waiting() -
2263  *
2264  *      Called from lock manager to report beginning or end of a lock wait.
2265  *
2266  * NB: this *must* be able to survive being called before MyBEEntry has been
2267  * initialized.
2268  * ----------
2269  */
2270 void
2271 pgstat_report_waiting(bool waiting)
2272 {
2273         volatile PgBackendStatus *beentry = MyBEEntry;
2274
2275         if (!pgstat_track_activities || !beentry)
2276                 return;
2277
2278         /*
2279          * Since this is a single-byte field in a struct that only this process
2280          * may modify, there seems no need to bother with the st_changecount
2281          * protocol.  The update must appear atomic in any case.
2282          */
2283         beentry->st_waiting = waiting;
2284 }
2285
2286
2287 /* ----------
2288  * pgstat_read_current_status() -
2289  *
2290  *      Copy the current contents of the PgBackendStatus array to local memory,
2291  *      if not already done in this transaction.
2292  * ----------
2293  */
2294 static void
2295 pgstat_read_current_status(void)
2296 {
2297         volatile PgBackendStatus *beentry;
2298         PgBackendStatus *localtable;
2299         PgBackendStatus *localentry;
2300         char                    *localactivity;
2301         int                     i;
2302
2303         Assert(!pgStatRunningInCollector);
2304         if (localBackendStatusTable)
2305                 return;                                 /* already done */
2306
2307         pgstat_setup_memcxt();
2308
2309         localtable = (PgBackendStatus *)
2310                 MemoryContextAlloc(pgStatLocalContext,
2311                                                    sizeof(PgBackendStatus) * MaxBackends);
2312         localactivity = (char *)
2313                 MemoryContextAlloc(pgStatLocalContext,
2314                                                    pgstat_track_activity_query_size * MaxBackends);
2315         localNumBackends = 0;
2316
2317         beentry = BackendStatusArray;
2318         localentry = localtable;
2319         for (i = 1; i <= MaxBackends; i++)
2320         {
2321                 /*
2322                  * Follow the protocol of retrying if st_changecount changes while we
2323                  * copy the entry, or if it's odd.  (The check for odd is needed to
2324                  * cover the case where we are able to completely copy the entry while
2325                  * the source backend is between increment steps.)      We use a volatile
2326                  * pointer here to ensure the compiler doesn't try to get cute.
2327                  */
2328                 for (;;)
2329                 {
2330                         int                     save_changecount = beentry->st_changecount;
2331
2332                         localentry->st_procpid = beentry->st_procpid;
2333                         if (localentry->st_procpid > 0)
2334                         {
2335                                 memcpy(localentry, (char *) beentry, sizeof(PgBackendStatus));
2336                                 /*
2337                                  * strcpy is safe even if the string is modified concurrently,
2338                                  * because there's always a \0 at the end of the buffer.
2339                                  */
2340                                 strcpy(localactivity, (char *) beentry->st_activity);
2341                                 localentry->st_activity = localactivity;
2342                         }
2343
2344                         if (save_changecount == beentry->st_changecount &&
2345                                 (save_changecount & 1) == 0)
2346                                 break;
2347
2348                         /* Make sure we can break out of loop if stuck... */
2349                         CHECK_FOR_INTERRUPTS();
2350                 }
2351
2352                 beentry++;
2353                 /* Only valid entries get included into the local array */
2354                 if (localentry->st_procpid > 0)
2355                 {
2356                         localentry++;
2357                         localactivity += pgstat_track_activity_query_size;
2358                         localNumBackends++;
2359                 }
2360         }
2361
2362         /* Set the pointer only after completion of a valid table */
2363         localBackendStatusTable = localtable;
2364 }
2365
2366
2367 /* ----------
2368  * pgstat_get_backend_current_activity() -
2369  *
2370  *      Return a string representing the current activity of the backend with
2371  *      the specified PID.  This looks directly at the BackendStatusArray,
2372  *      and so will provide current information regardless of the age of our
2373  *      transaction's snapshot of the status array.
2374  *
2375  *      It is the caller's responsibility to invoke this only for backends whose
2376  *      state is expected to remain stable while the result is in use.  The
2377  *      only current use is in deadlock reporting, where we can expect that
2378  *      the target backend is blocked on a lock.  (There are corner cases
2379  *      where the target's wait could get aborted while we are looking at it,
2380  *      but the very worst consequence is to return a pointer to a string
2381  *      that's been changed, so we won't worry too much.)
2382  *
2383  *      Note: return strings for special cases match pg_stat_get_backend_activity.
2384  * ----------
2385  */
2386 const char *
2387 pgstat_get_backend_current_activity(int pid, bool checkUser)
2388 {
2389         PgBackendStatus *beentry;
2390         int                     i;
2391
2392         beentry = BackendStatusArray;
2393         for (i = 1; i <= MaxBackends; i++)
2394         {
2395                 /*
2396                  * Although we expect the target backend's entry to be stable, that
2397                  * doesn't imply that anyone else's is.  To avoid identifying the
2398                  * wrong backend, while we check for a match to the desired PID we
2399                  * must follow the protocol of retrying if st_changecount changes
2400                  * while we examine the entry, or if it's odd.  (This might be
2401                  * unnecessary, since fetching or storing an int is almost certainly
2402                  * atomic, but let's play it safe.)  We use a volatile pointer here
2403                  * to ensure the compiler doesn't try to get cute.
2404                  */
2405                 volatile PgBackendStatus *vbeentry = beentry;
2406                 bool    found;
2407
2408                 for (;;)
2409                 {
2410                         int                     save_changecount = vbeentry->st_changecount;
2411
2412                         found = (vbeentry->st_procpid == pid);
2413
2414                         if (save_changecount == vbeentry->st_changecount &&
2415                                 (save_changecount & 1) == 0)
2416                                 break;
2417
2418                         /* Make sure we can break out of loop if stuck... */
2419                         CHECK_FOR_INTERRUPTS();
2420                 }
2421
2422                 if (found)
2423                 {
2424                         /* Now it is safe to use the non-volatile pointer */
2425                         if (checkUser && !superuser() && beentry->st_userid != GetUserId())
2426                                 return "<insufficient privilege>";
2427                         else if (*(beentry->st_activity) == '\0')
2428                                 return "<command string not enabled>";
2429                         else
2430                                 return beentry->st_activity;
2431                 }
2432
2433                 beentry++;
2434         }
2435
2436         /* If we get here, caller is in error ... */
2437         return "<backend information not available>";
2438 }
2439
2440
2441 /* ------------------------------------------------------------
2442  * Local support functions follow
2443  * ------------------------------------------------------------
2444  */
2445
2446
2447 /* ----------
2448  * pgstat_setheader() -
2449  *
2450  *              Set common header fields in a statistics message
2451  * ----------
2452  */
2453 static void
2454 pgstat_setheader(PgStat_MsgHdr *hdr, StatMsgType mtype)
2455 {
2456         hdr->m_type = mtype;
2457 }
2458
2459
2460 /* ----------
2461  * pgstat_send() -
2462  *
2463  *              Send out one statistics message to the collector
2464  * ----------
2465  */
2466 static void
2467 pgstat_send(void *msg, int len)
2468 {
2469         int                     rc;
2470
2471         if (pgStatSock < 0)
2472                 return;
2473
2474         ((PgStat_MsgHdr *) msg)->m_size = len;
2475
2476         /* We'll retry after EINTR, but ignore all other failures */
2477         do
2478         {
2479                 rc = send(pgStatSock, msg, len, 0);
2480         } while (rc < 0 && errno == EINTR);
2481
2482 #ifdef USE_ASSERT_CHECKING
2483         /* In debug builds, log send failures ... */
2484         if (rc < 0)
2485                 elog(LOG, "could not send to statistics collector: %m");
2486 #endif
2487 }
2488
2489 /* ----------
2490  * pgstat_send_bgwriter() -
2491  *
2492  *              Send bgwriter statistics to the collector
2493  * ----------
2494  */
2495 void
2496 pgstat_send_bgwriter(void)
2497 {
2498         /* We assume this initializes to zeroes */
2499         static const PgStat_MsgBgWriter all_zeroes;
2500
2501         /*
2502          * This function can be called even if nothing at all has happened. In
2503          * this case, avoid sending a completely empty message to the stats
2504          * collector.
2505          */
2506         if (memcmp(&BgWriterStats, &all_zeroes, sizeof(PgStat_MsgBgWriter)) == 0)
2507                 return;
2508
2509         /*
2510          * Prepare and send the message
2511          */
2512         pgstat_setheader(&BgWriterStats.m_hdr, PGSTAT_MTYPE_BGWRITER);
2513         pgstat_send(&BgWriterStats, sizeof(BgWriterStats));
2514
2515         /*
2516          * Clear out the statistics buffer, so it can be re-used.
2517          */
2518         MemSet(&BgWriterStats, 0, sizeof(BgWriterStats));
2519 }
2520
2521
2522 /* ----------
2523  * PgstatCollectorMain() -
2524  *
2525  *      Start up the statistics collector process.      This is the body of the
2526  *      postmaster child process.
2527  *
2528  *      The argc/argv parameters are valid only in EXEC_BACKEND case.
2529  * ----------
2530  */
2531 NON_EXEC_STATIC void
2532 PgstatCollectorMain(int argc, char *argv[])
2533 {
2534         struct itimerval write_timeout;
2535         bool            need_timer = false;
2536         int                     len;
2537         PgStat_Msg      msg;
2538
2539 #ifndef WIN32
2540 #ifdef HAVE_POLL
2541         struct pollfd input_fd;
2542 #else
2543         struct timeval sel_timeout;
2544         fd_set          rfds;
2545 #endif
2546 #endif
2547
2548         IsUnderPostmaster = true;       /* we are a postmaster subprocess now */
2549
2550         MyProcPid = getpid();           /* reset MyProcPid */
2551
2552         MyStartTime = time(NULL);       /* record Start Time for logging */
2553
2554         /*
2555          * If possible, make this process a group leader, so that the postmaster
2556          * can signal any child processes too.  (pgstat probably never has any
2557          * child processes, but for consistency we make all postmaster child
2558          * processes do this.)
2559          */
2560 #ifdef HAVE_SETSID
2561         if (setsid() < 0)
2562                 elog(FATAL, "setsid() failed: %m");
2563 #endif
2564
2565         /*
2566          * Ignore all signals usually bound to some action in the postmaster,
2567          * except SIGQUIT and SIGALRM.
2568          */
2569         pqsignal(SIGHUP, SIG_IGN);
2570         pqsignal(SIGINT, SIG_IGN);
2571         pqsignal(SIGTERM, SIG_IGN);
2572         pqsignal(SIGQUIT, pgstat_exit);
2573         pqsignal(SIGALRM, force_statwrite);
2574         pqsignal(SIGPIPE, SIG_IGN);
2575         pqsignal(SIGUSR1, SIG_IGN);
2576         pqsignal(SIGUSR2, SIG_IGN);
2577         pqsignal(SIGCHLD, SIG_DFL);
2578         pqsignal(SIGTTIN, SIG_DFL);
2579         pqsignal(SIGTTOU, SIG_DFL);
2580         pqsignal(SIGCONT, SIG_DFL);
2581         pqsignal(SIGWINCH, SIG_DFL);
2582         PG_SETMASK(&UnBlockSig);
2583
2584         /*
2585          * Identify myself via ps
2586          */
2587         init_ps_display("stats collector process", "", "", "");
2588
2589         /*
2590          * Arrange to write the initial status file right away
2591          */
2592         need_statwrite = true;
2593
2594         /* Preset the delay between status file writes */
2595         MemSet(&write_timeout, 0, sizeof(struct itimerval));
2596         write_timeout.it_value.tv_sec = PGSTAT_STAT_INTERVAL / 1000;
2597         write_timeout.it_value.tv_usec = (PGSTAT_STAT_INTERVAL % 1000) * 1000;
2598
2599         /*
2600          * Read in an existing statistics stats file or initialize the stats to
2601          * zero.
2602          */
2603         pgStatRunningInCollector = true;
2604         pgStatDBHash = pgstat_read_statsfile(InvalidOid, true);
2605
2606         /*
2607          * Setup the descriptor set for select(2).      Since only one bit in the set
2608          * ever changes, we need not repeat FD_ZERO each time.
2609          */
2610 #if !defined(HAVE_POLL) && !defined(WIN32)
2611         FD_ZERO(&rfds);
2612 #endif
2613
2614         /*
2615          * Loop to process messages until we get SIGQUIT or detect ungraceful
2616          * death of our parent postmaster.
2617          *
2618          * For performance reasons, we don't want to do a PostmasterIsAlive() test
2619          * after every message; instead, do it at statwrite time and if
2620          * select()/poll() is interrupted by timeout.
2621          */
2622         for (;;)
2623         {
2624                 int                     got_data;
2625
2626                 /*
2627                  * Quit if we get SIGQUIT from the postmaster.
2628                  */
2629                 if (need_exit)
2630                         break;
2631
2632                 /*
2633                  * If time to write the stats file, do so.      Note that the alarm
2634                  * interrupt isn't re-enabled immediately, but only after we next
2635                  * receive a stats message; so no cycles are wasted when there is
2636                  * nothing going on.
2637                  */
2638                 if (need_statwrite)
2639                 {
2640                         /* Check for postmaster death; if so we'll write file below */
2641                         if (!PostmasterIsAlive(true))
2642                                 break;
2643
2644                         pgstat_write_statsfile(false);
2645                         need_statwrite = false;
2646                         need_timer = true;
2647                 }
2648
2649                 /*
2650                  * Wait for a message to arrive; but not for more than
2651                  * PGSTAT_SELECT_TIMEOUT seconds. (This determines how quickly we will
2652                  * shut down after an ungraceful postmaster termination; so it needn't
2653                  * be very fast.  However, on some systems SIGQUIT won't interrupt the
2654                  * poll/select call, so this also limits speed of response to SIGQUIT,
2655                  * which is more important.)
2656                  *
2657                  * We use poll(2) if available, otherwise select(2). Win32 has its own
2658                  * implementation.
2659                  */
2660 #ifndef WIN32
2661 #ifdef HAVE_POLL
2662                 input_fd.fd = pgStatSock;
2663                 input_fd.events = POLLIN | POLLERR;
2664                 input_fd.revents = 0;
2665
2666                 if (poll(&input_fd, 1, PGSTAT_SELECT_TIMEOUT * 1000) < 0)
2667                 {
2668                         if (errno == EINTR)
2669                                 continue;
2670                         ereport(ERROR,
2671                                         (errcode_for_socket_access(),
2672                                          errmsg("poll() failed in statistics collector: %m")));
2673                 }
2674
2675                 got_data = (input_fd.revents != 0);
2676 #else                                                   /* !HAVE_POLL */
2677
2678                 FD_SET(pgStatSock, &rfds);
2679
2680                 /*
2681                  * timeout struct is modified by select() on some operating systems,
2682                  * so re-fill it each time.
2683                  */
2684                 sel_timeout.tv_sec = PGSTAT_SELECT_TIMEOUT;
2685                 sel_timeout.tv_usec = 0;
2686
2687                 if (select(pgStatSock + 1, &rfds, NULL, NULL, &sel_timeout) < 0)
2688                 {
2689                         if (errno == EINTR)
2690                                 continue;
2691                         ereport(ERROR,
2692                                         (errcode_for_socket_access(),
2693                                          errmsg("select() failed in statistics collector: %m")));
2694                 }
2695
2696                 got_data = FD_ISSET(pgStatSock, &rfds);
2697 #endif   /* HAVE_POLL */
2698 #else                                                   /* WIN32 */
2699                 got_data = pgwin32_waitforsinglesocket(pgStatSock, FD_READ,
2700                                                                                            PGSTAT_SELECT_TIMEOUT * 1000);
2701 #endif
2702
2703                 /*
2704                  * If there is a message on the socket, read it and check for
2705                  * validity.
2706                  */
2707                 if (got_data)
2708                 {
2709                         len = recv(pgStatSock, (char *) &msg,
2710                                            sizeof(PgStat_Msg), 0);
2711                         if (len < 0)
2712                         {
2713                                 if (errno == EINTR)
2714                                         continue;
2715                                 ereport(ERROR,
2716                                                 (errcode_for_socket_access(),
2717                                                  errmsg("could not read statistics message: %m")));
2718                         }
2719
2720                         /*
2721                          * We ignore messages that are smaller than our common header
2722                          */
2723                         if (len < sizeof(PgStat_MsgHdr))
2724                                 continue;
2725
2726                         /*
2727                          * The received length must match the length in the header
2728                          */
2729                         if (msg.msg_hdr.m_size != len)
2730                                 continue;
2731
2732                         /*
2733                          * O.K. - we accept this message.  Process it.
2734                          */
2735                         switch (msg.msg_hdr.m_type)
2736                         {
2737                                 case PGSTAT_MTYPE_DUMMY:
2738                                         break;
2739
2740                                 case PGSTAT_MTYPE_TABSTAT:
2741                                         pgstat_recv_tabstat((PgStat_MsgTabstat *) &msg, len);
2742                                         break;
2743
2744                                 case PGSTAT_MTYPE_TABPURGE:
2745                                         pgstat_recv_tabpurge((PgStat_MsgTabpurge *) &msg, len);
2746                                         break;
2747
2748                                 case PGSTAT_MTYPE_DROPDB:
2749                                         pgstat_recv_dropdb((PgStat_MsgDropdb *) &msg, len);
2750                                         break;
2751
2752                                 case PGSTAT_MTYPE_RESETCOUNTER:
2753                                         pgstat_recv_resetcounter((PgStat_MsgResetcounter *) &msg,
2754                                                                                          len);
2755                                         break;
2756
2757                                 case PGSTAT_MTYPE_AUTOVAC_START:
2758                                         pgstat_recv_autovac((PgStat_MsgAutovacStart *) &msg, len);
2759                                         break;
2760
2761                                 case PGSTAT_MTYPE_VACUUM:
2762                                         pgstat_recv_vacuum((PgStat_MsgVacuum *) &msg, len);
2763                                         break;
2764
2765                                 case PGSTAT_MTYPE_ANALYZE:
2766                                         pgstat_recv_analyze((PgStat_MsgAnalyze *) &msg, len);
2767                                         break;
2768
2769                                 case PGSTAT_MTYPE_BGWRITER:
2770                                         pgstat_recv_bgwriter((PgStat_MsgBgWriter *) &msg, len);
2771                                         break;
2772
2773                                 case PGSTAT_MTYPE_FUNCSTAT:
2774                                         pgstat_recv_funcstat((PgStat_MsgFuncstat *) &msg, len);
2775                                         break;
2776
2777                                 case PGSTAT_MTYPE_FUNCPURGE:
2778                                         pgstat_recv_funcpurge((PgStat_MsgFuncpurge *) &msg, len);
2779                                         break;
2780
2781                                 default:
2782                                         break;
2783                         }
2784
2785                         /*
2786                          * If this is the first message after we wrote the stats file the
2787                          * last time, enable the alarm interrupt to make it be written
2788                          * again later.
2789                          */
2790                         if (need_timer)
2791                         {
2792                                 if (setitimer(ITIMER_REAL, &write_timeout, NULL))
2793                                         ereport(ERROR,
2794                                         (errmsg("could not set statistics collector timer: %m")));
2795                                 need_timer = false;
2796                         }
2797                 }
2798                 else
2799                 {
2800                         /*
2801                          * We can only get here if the select/poll timeout elapsed. Check
2802                          * for postmaster death.
2803                          */
2804                         if (!PostmasterIsAlive(true))
2805                                 break;
2806                 }
2807         }                                                       /* end of message-processing loop */
2808
2809         /*
2810          * Save the final stats to reuse at next startup.
2811          */
2812         pgstat_write_statsfile(true);
2813
2814         exit(0);
2815 }
2816
2817
2818 /* SIGQUIT signal handler for collector process */
2819 static void
2820 pgstat_exit(SIGNAL_ARGS)
2821 {
2822         need_exit = true;
2823 }
2824
2825 /* SIGALRM signal handler for collector process */
2826 static void
2827 force_statwrite(SIGNAL_ARGS)
2828 {
2829         need_statwrite = true;
2830 }
2831
2832
2833 /*
2834  * Lookup the hash table entry for the specified database. If no hash
2835  * table entry exists, initialize it, if the create parameter is true.
2836  * Else, return NULL.
2837  */
2838 static PgStat_StatDBEntry *
2839 pgstat_get_db_entry(Oid databaseid, bool create)
2840 {
2841         PgStat_StatDBEntry *result;
2842         bool            found;
2843         HASHACTION      action = (create ? HASH_ENTER : HASH_FIND);
2844
2845         /* Lookup or create the hash table entry for this database */
2846         result = (PgStat_StatDBEntry *) hash_search(pgStatDBHash,
2847                                                                                                 &databaseid,
2848                                                                                                 action, &found);
2849
2850         if (!create && !found)
2851                 return NULL;
2852
2853         /* If not found, initialize the new one. */
2854         if (!found)
2855         {
2856                 HASHCTL         hash_ctl;
2857
2858                 result->tables = NULL;
2859                 result->functions = NULL;
2860                 result->n_xact_commit = 0;
2861                 result->n_xact_rollback = 0;
2862                 result->n_blocks_fetched = 0;
2863                 result->n_blocks_hit = 0;
2864                 result->n_tuples_returned = 0;
2865                 result->n_tuples_fetched = 0;
2866                 result->n_tuples_inserted = 0;
2867                 result->n_tuples_updated = 0;
2868                 result->n_tuples_deleted = 0;
2869                 result->last_autovac_time = 0;
2870
2871                 memset(&hash_ctl, 0, sizeof(hash_ctl));
2872                 hash_ctl.keysize = sizeof(Oid);
2873                 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
2874                 hash_ctl.hash = oid_hash;
2875                 result->tables = hash_create("Per-database table",
2876                                                                          PGSTAT_TAB_HASH_SIZE,
2877                                                                          &hash_ctl,
2878                                                                          HASH_ELEM | HASH_FUNCTION);
2879
2880                 hash_ctl.keysize = sizeof(Oid);
2881                 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
2882                 hash_ctl.hash = oid_hash;
2883                 result->functions = hash_create("Per-database function",
2884                                                                                 PGSTAT_FUNCTION_HASH_SIZE,
2885                                                                                 &hash_ctl,
2886                                                                                 HASH_ELEM | HASH_FUNCTION);
2887         }
2888
2889         return result;
2890 }
2891
2892
2893 /* ----------
2894  * pgstat_write_statsfile() -
2895  *
2896  *      Tell the news.
2897  *      If writing to the permanent file (happens when the collector is
2898  *      shutting down only), remove the temporary file so that backends
2899  *      starting up under a new postmaster can't read the old data before
2900  *      the new collector is ready.
2901  * ----------
2902  */
2903 static void
2904 pgstat_write_statsfile(bool permanent)
2905 {
2906         HASH_SEQ_STATUS hstat;
2907         HASH_SEQ_STATUS tstat;
2908         HASH_SEQ_STATUS fstat;
2909         PgStat_StatDBEntry *dbentry;
2910         PgStat_StatTabEntry *tabentry;
2911         PgStat_StatFuncEntry *funcentry;
2912         FILE       *fpout;
2913         int32           format_id;
2914         const char *tmpfile = permanent?PGSTAT_STAT_PERMANENT_TMPFILE:PGSTAT_STAT_TMPFILE;
2915         const char *statfile = permanent?PGSTAT_STAT_PERMANENT_FILENAME:PGSTAT_STAT_FILENAME;
2916
2917         /*
2918          * Open the statistics temp file to write out the current values.
2919          */
2920         fpout = fopen(tmpfile, PG_BINARY_W);
2921         if (fpout == NULL)
2922         {
2923                 ereport(LOG,
2924                                 (errcode_for_file_access(),
2925                                  errmsg("could not open temporary statistics file \"%s\": %m",
2926                                                 tmpfile)));
2927                 return;
2928         }
2929
2930         /*
2931          * Write the file header --- currently just a format ID.
2932          */
2933         format_id = PGSTAT_FILE_FORMAT_ID;
2934         fwrite(&format_id, sizeof(format_id), 1, fpout);
2935
2936         /*
2937          * Write global stats struct
2938          */
2939         fwrite(&globalStats, sizeof(globalStats), 1, fpout);
2940
2941         /*
2942          * Walk through the database table.
2943          */
2944         hash_seq_init(&hstat, pgStatDBHash);
2945         while ((dbentry = (PgStat_StatDBEntry *) hash_seq_search(&hstat)) != NULL)
2946         {
2947                 /*
2948                  * Write out the DB entry including the number of live backends. We
2949                  * don't write the tables or functions pointers, since they're of
2950                  * no use to any other process.
2951                  */
2952                 fputc('D', fpout);
2953                 fwrite(dbentry, offsetof(PgStat_StatDBEntry, tables), 1, fpout);
2954
2955                 /*
2956                  * Walk through the database's access stats per table.
2957                  */
2958                 hash_seq_init(&tstat, dbentry->tables);
2959                 while ((tabentry = (PgStat_StatTabEntry *) hash_seq_search(&tstat)) != NULL)
2960                 {
2961                         fputc('T', fpout);
2962                         fwrite(tabentry, sizeof(PgStat_StatTabEntry), 1, fpout);
2963                 }
2964
2965                 /*
2966                  * Walk through the database's function stats table.
2967                  */
2968                 hash_seq_init(&fstat, dbentry->functions);
2969                 while ((funcentry = (PgStat_StatFuncEntry *) hash_seq_search(&fstat)) != NULL)
2970                 {
2971                         fputc('F', fpout);
2972                         fwrite(funcentry, sizeof(PgStat_StatFuncEntry), 1, fpout);
2973                 }
2974
2975                 /*
2976                  * Mark the end of this DB
2977                  */
2978                 fputc('d', fpout);
2979         }
2980
2981         /*
2982          * No more output to be done. Close the temp file and replace the old
2983          * pgstat.stat with it.  The ferror() check replaces testing for error
2984          * after each individual fputc or fwrite above.
2985          */
2986         fputc('E', fpout);
2987
2988         if (ferror(fpout))
2989         {
2990                 ereport(LOG,
2991                                 (errcode_for_file_access(),
2992                            errmsg("could not write temporary statistics file \"%s\": %m",
2993                                           tmpfile)));
2994                 fclose(fpout);
2995                 unlink(tmpfile);
2996         }
2997         else if (fclose(fpout) < 0)
2998         {
2999                 ereport(LOG,
3000                                 (errcode_for_file_access(),
3001                            errmsg("could not close temporary statistics file \"%s\": %m",
3002                                           tmpfile)));
3003                 unlink(tmpfile);
3004         }
3005         else if (rename(tmpfile, statfile) < 0)
3006         {
3007                 ereport(LOG,
3008                                 (errcode_for_file_access(),
3009                                  errmsg("could not rename temporary statistics file \"%s\" to \"%s\": %m",
3010                                                 tmpfile, statfile)));
3011                 unlink(tmpfile);
3012         }
3013
3014         if (permanent)
3015                 unlink(PGSTAT_STAT_FILENAME);
3016 }
3017
3018
3019 /* ----------
3020  * pgstat_read_statsfile() -
3021  *
3022  *      Reads in an existing statistics collector file and initializes the
3023  *      databases' hash table (whose entries point to the tables' hash tables).
3024  * ----------
3025  */
3026 static HTAB *
3027 pgstat_read_statsfile(Oid onlydb, bool permanent)
3028 {
3029         PgStat_StatDBEntry *dbentry;
3030         PgStat_StatDBEntry dbbuf;
3031         PgStat_StatTabEntry *tabentry;
3032         PgStat_StatTabEntry tabbuf;
3033         PgStat_StatFuncEntry funcbuf;
3034         PgStat_StatFuncEntry *funcentry;
3035         HASHCTL         hash_ctl;
3036         HTAB       *dbhash;
3037         HTAB       *tabhash = NULL;
3038         HTAB       *funchash = NULL;
3039         FILE       *fpin;
3040         int32           format_id;
3041         bool            found;
3042         const char *statfile = permanent?PGSTAT_STAT_PERMANENT_FILENAME:PGSTAT_STAT_FILENAME;
3043
3044         /*
3045          * The tables will live in pgStatLocalContext.
3046          */
3047         pgstat_setup_memcxt();
3048
3049         /*
3050          * Create the DB hashtable
3051          */
3052         memset(&hash_ctl, 0, sizeof(hash_ctl));
3053         hash_ctl.keysize = sizeof(Oid);
3054         hash_ctl.entrysize = sizeof(PgStat_StatDBEntry);
3055         hash_ctl.hash = oid_hash;
3056         hash_ctl.hcxt = pgStatLocalContext;
3057         dbhash = hash_create("Databases hash", PGSTAT_DB_HASH_SIZE, &hash_ctl,
3058                                                  HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3059
3060         /*
3061          * Clear out global statistics so they start from zero in case we can't
3062          * load an existing statsfile.
3063          */
3064         memset(&globalStats, 0, sizeof(globalStats));
3065
3066         /*
3067          * Try to open the status file. If it doesn't exist, the backends simply
3068          * return zero for anything and the collector simply starts from scratch
3069          * with empty counters.
3070          */
3071         if ((fpin = AllocateFile(statfile, PG_BINARY_R)) == NULL)
3072                 return dbhash;
3073
3074         /*
3075          * Verify it's of the expected format.
3076          */
3077         if (fread(&format_id, 1, sizeof(format_id), fpin) != sizeof(format_id)
3078                 || format_id != PGSTAT_FILE_FORMAT_ID)
3079         {
3080                 ereport(pgStatRunningInCollector ? LOG : WARNING,
3081                                 (errmsg("corrupted pgstat.stat file")));
3082                 goto done;
3083         }
3084
3085         /*
3086          * Read global stats struct
3087          */
3088         if (fread(&globalStats, 1, sizeof(globalStats), fpin) != sizeof(globalStats))
3089         {
3090                 ereport(pgStatRunningInCollector ? LOG : WARNING,
3091                                 (errmsg("corrupted pgstat.stat file")));
3092                 goto done;
3093         }
3094
3095         /*
3096          * We found an existing collector stats file. Read it and put all the
3097          * hashtable entries into place.
3098          */
3099         for (;;)
3100         {
3101                 switch (fgetc(fpin))
3102                 {
3103                                 /*
3104                                  * 'D'  A PgStat_StatDBEntry struct describing a database
3105                                  * follows. Subsequently, zero to many 'T' and 'F' entries
3106                                  * will follow until a 'd' is encountered.
3107                                  */
3108                         case 'D':
3109                                 if (fread(&dbbuf, 1, offsetof(PgStat_StatDBEntry, tables),
3110                                                   fpin) != offsetof(PgStat_StatDBEntry, tables))
3111                                 {
3112                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3113                                                         (errmsg("corrupted pgstat.stat file")));
3114                                         goto done;
3115                                 }
3116
3117                                 /*
3118                                  * Add to the DB hash
3119                                  */
3120                                 dbentry = (PgStat_StatDBEntry *) hash_search(dbhash,
3121                                                                                                   (void *) &dbbuf.databaseid,
3122                                                                                                                          HASH_ENTER,
3123                                                                                                                          &found);
3124                                 if (found)
3125                                 {
3126                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3127                                                         (errmsg("corrupted pgstat.stat file")));
3128                                         goto done;
3129                                 }
3130
3131                                 memcpy(dbentry, &dbbuf, sizeof(PgStat_StatDBEntry));
3132                                 dbentry->tables = NULL;
3133                                 dbentry->functions = NULL;
3134
3135                                 /*
3136                                  * Don't collect tables if not the requested DB (or the
3137                                  * shared-table info)
3138                                  */
3139                                 if (onlydb != InvalidOid)
3140                                 {
3141                                         if (dbbuf.databaseid != onlydb &&
3142                                                 dbbuf.databaseid != InvalidOid)
3143                                                 break;
3144                                 }
3145
3146                                 memset(&hash_ctl, 0, sizeof(hash_ctl));
3147                                 hash_ctl.keysize = sizeof(Oid);
3148                                 hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3149                                 hash_ctl.hash = oid_hash;
3150                                 hash_ctl.hcxt = pgStatLocalContext;
3151                                 dbentry->tables = hash_create("Per-database table",
3152                                                                                           PGSTAT_TAB_HASH_SIZE,
3153                                                                                           &hash_ctl,
3154                                                                    HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3155
3156                                 hash_ctl.keysize = sizeof(Oid);
3157                                 hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3158                                 hash_ctl.hash = oid_hash;
3159                                 hash_ctl.hcxt = pgStatLocalContext;
3160                                 dbentry->functions = hash_create("Per-database function",
3161                                                                                                  PGSTAT_FUNCTION_HASH_SIZE,
3162                                                                                                  &hash_ctl,
3163                                                                    HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
3164                                 /*
3165                                  * Arrange that following records add entries to this
3166                                  * database's hash tables.
3167                                  */
3168                                 tabhash = dbentry->tables;
3169                                 funchash = dbentry->functions;
3170                                 break;
3171
3172                                 /*
3173                                  * 'd'  End of this database.
3174                                  */
3175                         case 'd':
3176                                 tabhash = NULL;
3177                                 funchash = NULL;
3178                                 break;
3179
3180                                 /*
3181                                  * 'T'  A PgStat_StatTabEntry follows.
3182                                  */
3183                         case 'T':
3184                                 if (fread(&tabbuf, 1, sizeof(PgStat_StatTabEntry),
3185                                                   fpin) != sizeof(PgStat_StatTabEntry))
3186                                 {
3187                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3188                                                         (errmsg("corrupted pgstat.stat file")));
3189                                         goto done;
3190                                 }
3191
3192                                 /*
3193                                  * Skip if table belongs to a not requested database.
3194                                  */
3195                                 if (tabhash == NULL)
3196                                         break;
3197
3198                                 tabentry = (PgStat_StatTabEntry *) hash_search(tabhash,
3199                                                                                                         (void *) &tabbuf.tableid,
3200                                                                                                                  HASH_ENTER, &found);
3201
3202                                 if (found)
3203                                 {
3204                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3205                                                         (errmsg("corrupted pgstat.stat file")));
3206                                         goto done;
3207                                 }
3208
3209                                 memcpy(tabentry, &tabbuf, sizeof(tabbuf));
3210                                 break;
3211
3212                                 /*
3213                                  * 'F'  A PgStat_StatFuncEntry follows.
3214                                  */
3215                         case 'F':
3216                                 if (fread(&funcbuf, 1, sizeof(PgStat_StatFuncEntry),
3217                                                   fpin) != sizeof(PgStat_StatFuncEntry))
3218                                 {
3219                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3220                                                         (errmsg("corrupted pgstat.stat file")));
3221                                         goto done;
3222                                 }
3223
3224                                 /*
3225                                  * Skip if function belongs to a not requested database.
3226                                  */
3227                                 if (funchash == NULL)
3228                                         break;
3229
3230                                 funcentry = (PgStat_StatFuncEntry *) hash_search(funchash,
3231                                                                                                         (void *) &funcbuf.functionid,
3232                                                                                                                  HASH_ENTER, &found);
3233
3234                                 if (found)
3235                                 {
3236                                         ereport(pgStatRunningInCollector ? LOG : WARNING,
3237                                                         (errmsg("corrupted pgstat.stat file")));
3238                                         goto done;
3239                                 }
3240
3241                                 memcpy(funcentry, &funcbuf, sizeof(funcbuf));
3242                                 break;
3243
3244                                 /*
3245                                  * 'E'  The EOF marker of a complete stats file.
3246                                  */
3247                         case 'E':
3248                                 goto done;
3249
3250                         default:
3251                                 ereport(pgStatRunningInCollector ? LOG : WARNING,
3252                                                 (errmsg("corrupted pgstat.stat file")));
3253                                 goto done;
3254                 }
3255         }
3256
3257 done:
3258         FreeFile(fpin);
3259
3260         if (permanent)
3261                 unlink(PGSTAT_STAT_PERMANENT_FILENAME);
3262
3263         return dbhash;
3264 }
3265
3266 /*
3267  * If not already done, read the statistics collector stats file into
3268  * some hash tables.  The results will be kept until pgstat_clear_snapshot()
3269  * is called (typically, at end of transaction).
3270  */
3271 static void
3272 backend_read_statsfile(void)
3273 {
3274         /* already read it? */
3275         if (pgStatDBHash)
3276                 return;
3277         Assert(!pgStatRunningInCollector);
3278
3279         /* Autovacuum launcher wants stats about all databases */
3280         if (IsAutoVacuumLauncherProcess())
3281                 pgStatDBHash = pgstat_read_statsfile(InvalidOid, false);
3282         else
3283                 pgStatDBHash = pgstat_read_statsfile(MyDatabaseId, false);
3284 }
3285
3286
3287 /* ----------
3288  * pgstat_setup_memcxt() -
3289  *
3290  *      Create pgStatLocalContext, if not already done.
3291  * ----------
3292  */
3293 static void
3294 pgstat_setup_memcxt(void)
3295 {
3296         if (!pgStatLocalContext)
3297                 pgStatLocalContext = AllocSetContextCreate(TopMemoryContext,
3298                                                                                                    "Statistics snapshot",
3299                                                                                                    ALLOCSET_SMALL_MINSIZE,
3300                                                                                                    ALLOCSET_SMALL_INITSIZE,
3301                                                                                                    ALLOCSET_SMALL_MAXSIZE);
3302 }
3303
3304
3305 /* ----------
3306  * pgstat_clear_snapshot() -
3307  *
3308  *      Discard any data collected in the current transaction.  Any subsequent
3309  *      request will cause new snapshots to be read.
3310  *
3311  *      This is also invoked during transaction commit or abort to discard
3312  *      the no-longer-wanted snapshot.
3313  * ----------
3314  */
3315 void
3316 pgstat_clear_snapshot(void)
3317 {
3318         /* Release memory, if any was allocated */
3319         if (pgStatLocalContext)
3320                 MemoryContextDelete(pgStatLocalContext);
3321
3322         /* Reset variables */
3323         pgStatLocalContext = NULL;
3324         pgStatDBHash = NULL;
3325         localBackendStatusTable = NULL;
3326         localNumBackends = 0;
3327 }
3328
3329
3330 /* ----------
3331  * pgstat_recv_tabstat() -
3332  *
3333  *      Count what the backend has done.
3334  * ----------
3335  */
3336 static void
3337 pgstat_recv_tabstat(PgStat_MsgTabstat *msg, int len)
3338 {
3339         PgStat_TableEntry *tabmsg = &(msg->m_entry[0]);
3340         PgStat_StatDBEntry *dbentry;
3341         PgStat_StatTabEntry *tabentry;
3342         int                     i;
3343         bool            found;
3344
3345         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
3346
3347         /*
3348          * Update database-wide stats.
3349          */
3350         dbentry->n_xact_commit += (PgStat_Counter) (msg->m_xact_commit);
3351         dbentry->n_xact_rollback += (PgStat_Counter) (msg->m_xact_rollback);
3352
3353         /*
3354          * Process all table entries in the message.
3355          */
3356         for (i = 0; i < msg->m_nentries; i++)
3357         {
3358                 tabentry = (PgStat_StatTabEntry *) hash_search(dbentry->tables,
3359                                                                                                   (void *) &(tabmsg[i].t_id),
3360                                                                                                            HASH_ENTER, &found);
3361
3362                 if (!found)
3363                 {
3364                         /*
3365                          * If it's a new table entry, initialize counters to the values we
3366                          * just got.
3367                          */
3368                         tabentry->numscans = tabmsg[i].t_counts.t_numscans;
3369                         tabentry->tuples_returned = tabmsg[i].t_counts.t_tuples_returned;
3370                         tabentry->tuples_fetched = tabmsg[i].t_counts.t_tuples_fetched;
3371                         tabentry->tuples_inserted = tabmsg[i].t_counts.t_tuples_inserted;
3372                         tabentry->tuples_updated = tabmsg[i].t_counts.t_tuples_updated;
3373                         tabentry->tuples_deleted = tabmsg[i].t_counts.t_tuples_deleted;
3374                         tabentry->tuples_hot_updated = tabmsg[i].t_counts.t_tuples_hot_updated;
3375                         tabentry->n_live_tuples = tabmsg[i].t_counts.t_new_live_tuples;
3376                         tabentry->n_dead_tuples = tabmsg[i].t_counts.t_new_dead_tuples;
3377                         tabentry->blocks_fetched = tabmsg[i].t_counts.t_blocks_fetched;
3378                         tabentry->blocks_hit = tabmsg[i].t_counts.t_blocks_hit;
3379
3380                         tabentry->last_anl_tuples = 0;
3381                         tabentry->vacuum_timestamp = 0;
3382                         tabentry->autovac_vacuum_timestamp = 0;
3383                         tabentry->analyze_timestamp = 0;
3384                         tabentry->autovac_analyze_timestamp = 0;
3385                 }
3386                 else
3387                 {
3388                         /*
3389                          * Otherwise add the values to the existing entry.
3390                          */
3391                         tabentry->numscans += tabmsg[i].t_counts.t_numscans;
3392                         tabentry->tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
3393                         tabentry->tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
3394                         tabentry->tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
3395                         tabentry->tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
3396                         tabentry->tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
3397                         tabentry->tuples_hot_updated += tabmsg[i].t_counts.t_tuples_hot_updated;
3398                         tabentry->n_live_tuples += tabmsg[i].t_counts.t_new_live_tuples;
3399                         tabentry->n_dead_tuples += tabmsg[i].t_counts.t_new_dead_tuples;
3400                         tabentry->blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
3401                         tabentry->blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
3402                 }
3403
3404                 /* Clamp n_live_tuples in case of negative new_live_tuples */
3405                 tabentry->n_live_tuples = Max(tabentry->n_live_tuples, 0);
3406                 /* Likewise for n_dead_tuples */
3407                 tabentry->n_dead_tuples = Max(tabentry->n_dead_tuples, 0);
3408
3409                 /*
3410                  * Add per-table stats to the per-database entry, too.
3411                  */
3412                 dbentry->n_tuples_returned += tabmsg[i].t_counts.t_tuples_returned;
3413                 dbentry->n_tuples_fetched += tabmsg[i].t_counts.t_tuples_fetched;
3414                 dbentry->n_tuples_inserted += tabmsg[i].t_counts.t_tuples_inserted;
3415                 dbentry->n_tuples_updated += tabmsg[i].t_counts.t_tuples_updated;
3416                 dbentry->n_tuples_deleted += tabmsg[i].t_counts.t_tuples_deleted;
3417                 dbentry->n_blocks_fetched += tabmsg[i].t_counts.t_blocks_fetched;
3418                 dbentry->n_blocks_hit += tabmsg[i].t_counts.t_blocks_hit;
3419         }
3420 }
3421
3422
3423 /* ----------
3424  * pgstat_recv_tabpurge() -
3425  *
3426  *      Arrange for dead table removal.
3427  * ----------
3428  */
3429 static void
3430 pgstat_recv_tabpurge(PgStat_MsgTabpurge *msg, int len)
3431 {
3432         PgStat_StatDBEntry *dbentry;
3433         int                     i;
3434
3435         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3436
3437         /*
3438          * No need to purge if we don't even know the database.
3439          */
3440         if (!dbentry || !dbentry->tables)
3441                 return;
3442
3443         /*
3444          * Process all table entries in the message.
3445          */
3446         for (i = 0; i < msg->m_nentries; i++)
3447         {
3448                 /* Remove from hashtable if present; we don't care if it's not. */
3449                 (void) hash_search(dbentry->tables,
3450                                                    (void *) &(msg->m_tableid[i]),
3451                                                    HASH_REMOVE, NULL);
3452         }
3453 }
3454
3455
3456 /* ----------
3457  * pgstat_recv_dropdb() -
3458  *
3459  *      Arrange for dead database removal
3460  * ----------
3461  */
3462 static void
3463 pgstat_recv_dropdb(PgStat_MsgDropdb *msg, int len)
3464 {
3465         PgStat_StatDBEntry *dbentry;
3466
3467         /*
3468          * Lookup the database in the hashtable.
3469          */
3470         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3471
3472         /*
3473          * If found, remove it.
3474          */
3475         if (dbentry)
3476         {
3477                 if (dbentry->tables != NULL)
3478                         hash_destroy(dbentry->tables);
3479                 if (dbentry->functions != NULL)
3480                         hash_destroy(dbentry->functions);
3481
3482                 if (hash_search(pgStatDBHash,
3483                                                 (void *) &(dbentry->databaseid),
3484                                                 HASH_REMOVE, NULL) == NULL)
3485                         ereport(ERROR,
3486                                         (errmsg("database hash table corrupted "
3487                                                         "during cleanup --- abort")));
3488         }
3489 }
3490
3491
3492 /* ----------
3493  * pgstat_recv_resetcounter() -
3494  *
3495  *      Reset the statistics for the specified database.
3496  * ----------
3497  */
3498 static void
3499 pgstat_recv_resetcounter(PgStat_MsgResetcounter *msg, int len)
3500 {
3501         HASHCTL         hash_ctl;
3502         PgStat_StatDBEntry *dbentry;
3503
3504         /*
3505          * Lookup the database in the hashtable.  Nothing to do if not there.
3506          */
3507         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3508
3509         if (!dbentry)
3510                 return;
3511
3512         /*
3513          * We simply throw away all the database's table entries by recreating a
3514          * new hash table for them.
3515          */
3516         if (dbentry->tables != NULL)
3517                 hash_destroy(dbentry->tables);
3518         if (dbentry->functions != NULL)
3519                 hash_destroy(dbentry->functions);
3520
3521         dbentry->tables = NULL;
3522         dbentry->functions = NULL;
3523         dbentry->n_xact_commit = 0;
3524         dbentry->n_xact_rollback = 0;
3525         dbentry->n_blocks_fetched = 0;
3526         dbentry->n_blocks_hit = 0;
3527
3528         memset(&hash_ctl, 0, sizeof(hash_ctl));
3529         hash_ctl.keysize = sizeof(Oid);
3530         hash_ctl.entrysize = sizeof(PgStat_StatTabEntry);
3531         hash_ctl.hash = oid_hash;
3532         dbentry->tables = hash_create("Per-database table",
3533                                                                   PGSTAT_TAB_HASH_SIZE,
3534                                                                   &hash_ctl,
3535                                                                   HASH_ELEM | HASH_FUNCTION);
3536
3537         hash_ctl.keysize = sizeof(Oid);
3538         hash_ctl.entrysize = sizeof(PgStat_StatFuncEntry);
3539         hash_ctl.hash = oid_hash;
3540         dbentry->functions = hash_create("Per-database function",
3541                                                                          PGSTAT_FUNCTION_HASH_SIZE,
3542                                                                          &hash_ctl,
3543                                                                          HASH_ELEM | HASH_FUNCTION);
3544 }
3545
3546 /* ----------
3547  * pgstat_recv_autovac() -
3548  *
3549  *      Process an autovacuum signalling message.
3550  * ----------
3551  */
3552 static void
3553 pgstat_recv_autovac(PgStat_MsgAutovacStart *msg, int len)
3554 {
3555         PgStat_StatDBEntry *dbentry;
3556
3557         /*
3558          * Lookup the database in the hashtable.  Don't create the entry if it
3559          * doesn't exist, because autovacuum may be processing a template
3560          * database.  If this isn't the case, the database is most likely to have
3561          * an entry already.  (If it doesn't, not much harm is done anyway --
3562          * it'll get created as soon as somebody actually uses the database.)
3563          */
3564         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3565         if (dbentry == NULL)
3566                 return;
3567
3568         /*
3569          * Store the last autovacuum time in the database entry.
3570          */
3571         dbentry->last_autovac_time = msg->m_start_time;
3572 }
3573
3574 /* ----------
3575  * pgstat_recv_vacuum() -
3576  *
3577  *      Process a VACUUM message.
3578  * ----------
3579  */
3580 static void
3581 pgstat_recv_vacuum(PgStat_MsgVacuum *msg, int len)
3582 {
3583         PgStat_StatDBEntry *dbentry;
3584         PgStat_StatTabEntry *tabentry;
3585
3586         /*
3587          * Don't create either the database or table entry if it doesn't already
3588          * exist.  This avoids bloating the stats with entries for stuff that is
3589          * only touched by vacuum and not by live operations.
3590          */
3591         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3592         if (dbentry == NULL)
3593                 return;
3594
3595         tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3596                                                    HASH_FIND, NULL);
3597         if (tabentry == NULL)
3598                 return;
3599
3600         if (msg->m_autovacuum)
3601                 tabentry->autovac_vacuum_timestamp = msg->m_vacuumtime;
3602         else
3603                 tabentry->vacuum_timestamp = msg->m_vacuumtime;
3604         tabentry->n_live_tuples = msg->m_tuples;
3605         /* Resetting dead_tuples to 0 is an approximation ... */
3606         tabentry->n_dead_tuples = 0;
3607         if (msg->m_analyze)
3608         {
3609                 tabentry->last_anl_tuples = msg->m_tuples;
3610                 if (msg->m_autovacuum)
3611                         tabentry->autovac_analyze_timestamp = msg->m_vacuumtime;
3612                 else
3613                         tabentry->analyze_timestamp = msg->m_vacuumtime;
3614         }
3615         else
3616         {
3617                 /* last_anl_tuples must never exceed n_live_tuples+n_dead_tuples */
3618                 tabentry->last_anl_tuples = Min(tabentry->last_anl_tuples,
3619                                                                                 msg->m_tuples);
3620         }
3621 }
3622
3623 /* ----------
3624  * pgstat_recv_analyze() -
3625  *
3626  *      Process an ANALYZE message.
3627  * ----------
3628  */
3629 static void
3630 pgstat_recv_analyze(PgStat_MsgAnalyze *msg, int len)
3631 {
3632         PgStat_StatDBEntry *dbentry;
3633         PgStat_StatTabEntry *tabentry;
3634
3635         /*
3636          * Don't create either the database or table entry if it doesn't already
3637          * exist.  This avoids bloating the stats with entries for stuff that is
3638          * only touched by analyze and not by live operations.
3639          */
3640         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3641         if (dbentry == NULL)
3642                 return;
3643
3644         tabentry = hash_search(dbentry->tables, &(msg->m_tableoid),
3645                                                    HASH_FIND, NULL);
3646         if (tabentry == NULL)
3647                 return;
3648
3649         if (msg->m_autovacuum)
3650                 tabentry->autovac_analyze_timestamp = msg->m_analyzetime;
3651         else
3652                 tabentry->analyze_timestamp = msg->m_analyzetime;
3653         tabentry->n_live_tuples = msg->m_live_tuples;
3654         tabentry->n_dead_tuples = msg->m_dead_tuples;
3655         tabentry->last_anl_tuples = msg->m_live_tuples + msg->m_dead_tuples;
3656 }
3657
3658
3659 /* ----------
3660  * pgstat_recv_bgwriter() -
3661  *
3662  *      Process a BGWRITER message.
3663  * ----------
3664  */
3665 static void
3666 pgstat_recv_bgwriter(PgStat_MsgBgWriter *msg, int len)
3667 {
3668         globalStats.timed_checkpoints += msg->m_timed_checkpoints;
3669         globalStats.requested_checkpoints += msg->m_requested_checkpoints;
3670         globalStats.buf_written_checkpoints += msg->m_buf_written_checkpoints;
3671         globalStats.buf_written_clean += msg->m_buf_written_clean;
3672         globalStats.maxwritten_clean += msg->m_maxwritten_clean;
3673         globalStats.buf_written_backend += msg->m_buf_written_backend;
3674         globalStats.buf_alloc += msg->m_buf_alloc;
3675 }
3676
3677 /* ----------
3678  * pgstat_recv_funcstat() -
3679  *
3680  *      Count what the backend has done.
3681  * ----------
3682  */
3683 static void
3684 pgstat_recv_funcstat(PgStat_MsgFuncstat *msg, int len)
3685 {
3686         PgStat_FunctionEntry *funcmsg = &(msg->m_entry[0]);
3687         PgStat_StatDBEntry *dbentry;
3688         PgStat_StatFuncEntry *funcentry;
3689         int                     i;
3690         bool            found;
3691
3692         dbentry = pgstat_get_db_entry(msg->m_databaseid, true);
3693
3694         /*
3695          * Process all function entries in the message.
3696          */
3697         for (i = 0; i < msg->m_nentries; i++, funcmsg++)
3698         {
3699                 funcentry = (PgStat_StatFuncEntry *) hash_search(dbentry->functions,
3700                                                                                                   (void *) &(funcmsg->f_id),
3701                                                                                                            HASH_ENTER, &found);
3702
3703                 if (!found)
3704                 {
3705                         /*
3706                          * If it's a new function entry, initialize counters to the values
3707                          * we just got.
3708                          */
3709                         funcentry->f_numcalls = funcmsg->f_numcalls;
3710                         funcentry->f_time = funcmsg->f_time;
3711                         funcentry->f_time_self = funcmsg->f_time_self;
3712                 }
3713                 else
3714                 {
3715                         /*
3716                          * Otherwise add the values to the existing entry.
3717                          */
3718                         funcentry->f_numcalls += funcmsg->f_numcalls;
3719                         funcentry->f_time += funcmsg->f_time;
3720                         funcentry->f_time_self += funcmsg->f_time_self;
3721                 }
3722         }
3723 }
3724
3725 /* ----------
3726  * pgstat_recv_funcpurge() -
3727  *
3728  *      Arrange for dead function removal.
3729  * ----------
3730  */
3731 static void
3732 pgstat_recv_funcpurge(PgStat_MsgFuncpurge *msg, int len)
3733 {
3734         PgStat_StatDBEntry *dbentry;
3735         int                     i;
3736
3737         dbentry = pgstat_get_db_entry(msg->m_databaseid, false);
3738
3739         /*
3740          * No need to purge if we don't even know the database.
3741          */
3742         if (!dbentry || !dbentry->functions)
3743                 return;
3744
3745         /*
3746          * Process all function entries in the message.
3747          */
3748         for (i = 0; i < msg->m_nentries; i++)
3749         {
3750                 /* Remove from hashtable if present; we don't care if it's not. */
3751                 (void) hash_search(dbentry->functions,
3752                                                    (void *) &(msg->m_functionid[i]),
3753                                                    HASH_REMOVE, NULL);
3754         }
3755 }