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