PostgreSQL Source Code  git master
backend_status.h File Reference
#include "datatype/timestamp.h"
#include "libpq/pqcomm.h"
#include "miscadmin.h"
#include "storage/backendid.h"
#include "utils/backend_progress.h"
Include dependency graph for backend_status.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  PgBackendSSLStatus
 
struct  PgBackendGSSStatus
 
struct  PgBackendStatus
 
struct  LocalPgBackendStatus
 

Macros

#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
 
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
 
#define pgstat_begin_read_activity(beentry, before_changecount)
 
#define pgstat_end_read_activity(beentry, after_changecount)
 
#define pgstat_read_activity_complete(before_changecount, after_changecount)
 

Typedefs

typedef enum BackendState BackendState
 
typedef struct PgBackendSSLStatus PgBackendSSLStatus
 
typedef struct PgBackendGSSStatus PgBackendGSSStatus
 
typedef struct PgBackendStatus PgBackendStatus
 
typedef struct LocalPgBackendStatus LocalPgBackendStatus
 

Enumerations

enum  BackendState {
  STATE_UNDEFINED , STATE_IDLE , STATE_RUNNING , STATE_IDLEINTRANSACTION ,
  STATE_FASTPATH , STATE_IDLEINTRANSACTION_ABORTED , STATE_DISABLED
}
 

Functions

Size BackendStatusShmemSize (void)
 
void CreateSharedBackendStatus (void)
 
void pgstat_beinit (void)
 
void pgstat_bestart (void)
 
void pgstat_clear_backend_activity_snapshot (void)
 
void pgstat_report_activity (BackendState state, const char *cmd_str)
 
void pgstat_report_query_id (uint64 query_id, bool force)
 
void pgstat_report_tempfile (size_t filesize)
 
void pgstat_report_appname (const char *appname)
 
void pgstat_report_xact_timestamp (TimestampTz tstamp)
 
const char * pgstat_get_backend_current_activity (int pid, bool checkUser)
 
const char * pgstat_get_crashed_backend_activity (int pid, char *buffer, int buflen)
 
uint64 pgstat_get_my_query_id (void)
 
int pgstat_fetch_stat_numbackends (void)
 
PgBackendStatuspgstat_get_beentry_by_backend_id (BackendId beid)
 
LocalPgBackendStatuspgstat_get_local_beentry_by_backend_id (BackendId beid)
 
LocalPgBackendStatuspgstat_get_local_beentry_by_index (int idx)
 
char * pgstat_clip_activity (const char *raw_activity)
 

Variables

PGDLLIMPORT bool pgstat_track_activities
 
PGDLLIMPORT int pgstat_track_activity_query_size
 
PGDLLIMPORT PgBackendStatusMyBEEntry
 

Macro Definition Documentation

◆ pgstat_begin_read_activity

#define pgstat_begin_read_activity (   beentry,
  before_changecount 
)
Value:
do { \
(before_changecount) = (beentry)->st_changecount; \
pg_read_barrier(); \
} while (0)

Definition at line 220 of file backend_status.h.

◆ PGSTAT_BEGIN_WRITE_ACTIVITY

#define PGSTAT_BEGIN_WRITE_ACTIVITY (   beentry)
Value:
do { \
START_CRIT_SECTION(); \
(beentry)->st_changecount++; \
pg_write_barrier(); \
} while (0)

Definition at line 205 of file backend_status.h.

◆ pgstat_end_read_activity

#define pgstat_end_read_activity (   beentry,
  after_changecount 
)
Value:
do { \
pg_read_barrier(); \
(after_changecount) = (beentry)->st_changecount; \
} while (0)

Definition at line 226 of file backend_status.h.

◆ PGSTAT_END_WRITE_ACTIVITY

#define PGSTAT_END_WRITE_ACTIVITY (   beentry)
Value:
do { \
pg_write_barrier(); \
(beentry)->st_changecount++; \
Assert(((beentry)->st_changecount & 1) == 0); \
END_CRIT_SECTION(); \
} while (0)

Definition at line 212 of file backend_status.h.

◆ pgstat_read_activity_complete

#define pgstat_read_activity_complete (   before_changecount,
  after_changecount 
)
Value:
((before_changecount) == (after_changecount) && \
((before_changecount) & 1) == 0)

Definition at line 232 of file backend_status.h.

Typedef Documentation

◆ BackendState

typedef enum BackendState BackendState

◆ LocalPgBackendStatus

◆ PgBackendGSSStatus

◆ PgBackendSSLStatus

◆ PgBackendStatus

Enumeration Type Documentation

◆ BackendState

Enumerator
STATE_UNDEFINED 
STATE_IDLE 
STATE_RUNNING 
STATE_IDLEINTRANSACTION 
STATE_FASTPATH 
STATE_IDLEINTRANSACTION_ABORTED 
STATE_DISABLED 

Definition at line 24 of file backend_status.h.

25 {
27  STATE_IDLE,
33 } BackendState;
BackendState
@ STATE_UNDEFINED
@ STATE_IDLEINTRANSACTION_ABORTED
@ STATE_IDLE
@ STATE_IDLEINTRANSACTION
@ STATE_DISABLED
@ STATE_FASTPATH
@ STATE_RUNNING

Function Documentation

◆ BackendStatusShmemSize()

Size BackendStatusShmemSize ( void  )

Definition at line 84 of file backend_status.c.

85 {
86  Size size;
87 
88  /* BackendStatusArray: */
90  /* BackendAppnameBuffer: */
91  size = add_size(size,
93  /* BackendClientHostnameBuffer: */
94  size = add_size(size,
96  /* BackendActivityBuffer: */
97  size = add_size(size,
99 #ifdef USE_SSL
100  /* BackendSslStatusBuffer: */
101  size = add_size(size,
103 #endif
104 #ifdef ENABLE_GSS
105  /* BackendGssStatusBuffer: */
106  size = add_size(size,
108 #endif
109  return size;
110 }
#define NumBackendStatSlots
int pgstat_track_activity_query_size
size_t Size
Definition: c.h:594
#define NAMEDATALEN
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

References add_size(), mul_size(), NAMEDATALEN, NumBackendStatSlots, and pgstat_track_activity_query_size.

Referenced by CalculateShmemSize().

◆ CreateSharedBackendStatus()

void CreateSharedBackendStatus ( void  )

Definition at line 117 of file backend_status.c.

118 {
119  Size size;
120  bool found;
121  int i;
122  char *buffer;
123 
124  /* Create or attach to the shared array */
127  ShmemInitStruct("Backend Status Array", size, &found);
128 
129  if (!found)
130  {
131  /*
132  * We're the first - initialize.
133  */
134  MemSet(BackendStatusArray, 0, size);
135  }
136 
137  /* Create or attach to the shared appname buffer */
139  BackendAppnameBuffer = (char *)
140  ShmemInitStruct("Backend Application Name Buffer", size, &found);
141 
142  if (!found)
143  {
144  MemSet(BackendAppnameBuffer, 0, size);
145 
146  /* Initialize st_appname pointers. */
147  buffer = BackendAppnameBuffer;
148  for (i = 0; i < NumBackendStatSlots; i++)
149  {
150  BackendStatusArray[i].st_appname = buffer;
151  buffer += NAMEDATALEN;
152  }
153  }
154 
155  /* Create or attach to the shared client hostname buffer */
157  BackendClientHostnameBuffer = (char *)
158  ShmemInitStruct("Backend Client Host Name Buffer", size, &found);
159 
160  if (!found)
161  {
163 
164  /* Initialize st_clienthostname pointers. */
166  for (i = 0; i < NumBackendStatSlots; i++)
167  {
169  buffer += NAMEDATALEN;
170  }
171  }
172 
173  /* Create or attach to the shared activity buffer */
176  BackendActivityBuffer = (char *)
177  ShmemInitStruct("Backend Activity Buffer",
179  &found);
180 
181  if (!found)
182  {
184 
185  /* Initialize st_activity pointers. */
186  buffer = BackendActivityBuffer;
187  for (i = 0; i < NumBackendStatSlots; i++)
188  {
191  }
192  }
193 
194 #ifdef USE_SSL
195  /* Create or attach to the shared SSL status buffer */
197  BackendSslStatusBuffer = (PgBackendSSLStatus *)
198  ShmemInitStruct("Backend SSL Status Buffer", size, &found);
199 
200  if (!found)
201  {
202  PgBackendSSLStatus *ptr;
203 
204  MemSet(BackendSslStatusBuffer, 0, size);
205 
206  /* Initialize st_sslstatus pointers. */
207  ptr = BackendSslStatusBuffer;
208  for (i = 0; i < NumBackendStatSlots; i++)
209  {
211  ptr++;
212  }
213  }
214 #endif
215 
216 #ifdef ENABLE_GSS
217  /* Create or attach to the shared GSSAPI status buffer */
219  BackendGssStatusBuffer = (PgBackendGSSStatus *)
220  ShmemInitStruct("Backend GSS Status Buffer", size, &found);
221 
222  if (!found)
223  {
224  PgBackendGSSStatus *ptr;
225 
226  MemSet(BackendGssStatusBuffer, 0, size);
227 
228  /* Initialize st_gssstatus pointers. */
229  ptr = BackendGssStatusBuffer;
230  for (i = 0; i < NumBackendStatSlots; i++)
231  {
233  ptr++;
234  }
235  }
236 #endif
237 }
static char * BackendClientHostnameBuffer
static char * BackendActivityBuffer
static char * BackendAppnameBuffer
static PgBackendStatus * BackendStatusArray
static Size BackendActivityBufferSize
#define MemSet(start, val, len)
Definition: c.h:1009
int i
Definition: isn.c:73
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
PgBackendGSSStatus * st_gssstatus
PgBackendSSLStatus * st_sslstatus
char * st_clienthostname

References BackendActivityBuffer, BackendActivityBufferSize, BackendAppnameBuffer, BackendClientHostnameBuffer, BackendStatusArray, i, MemSet, mul_size(), NAMEDATALEN, NumBackendStatSlots, pgstat_track_activity_query_size, ShmemInitStruct(), PgBackendStatus::st_activity_raw, PgBackendStatus::st_appname, PgBackendStatus::st_clienthostname, PgBackendStatus::st_gssstatus, and PgBackendStatus::st_sslstatus.

Referenced by CreateSharedMemoryAndSemaphores().

◆ pgstat_beinit()

void pgstat_beinit ( void  )

Definition at line 249 of file backend_status.c.

250 {
251  /* Initialize MyBEEntry */
253  {
256  }
257  else
258  {
259  /* Must be an auxiliary process */
261 
262  /*
263  * Assign the MyBEEntry for an auxiliary process. Since it doesn't
264  * have a BackendId, the slot is statically allocated based on the
265  * auxiliary process type (MyAuxProcType). Backends use slots indexed
266  * in the range from 1 to MaxBackends (inclusive), so we use
267  * MaxBackends + AuxBackendType + 1 as the index of the slot for an
268  * auxiliary process.
269  */
271  }
272 
273  /* Set up a process-exit hook to clean up */
275 }
AuxProcType MyAuxProcType
Definition: auxprocess.c:45
PgBackendStatus * MyBEEntry
static void pgstat_beshutdown_hook(int code, Datum arg)
#define InvalidBackendId
Definition: backendid.h:23
BackendId MyBackendId
Definition: globals.c:85
int MaxBackends
Definition: globals.c:140
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
Assert(fmt[strlen(fmt) - 1] !='\n')
@ NotAnAuxProcess
Definition: miscadmin.h:439

References Assert(), BackendStatusArray, InvalidBackendId, MaxBackends, MyAuxProcType, MyBackendId, MyBEEntry, NotAnAuxProcess, on_shmem_exit(), and pgstat_beshutdown_hook().

Referenced by AuxiliaryProcessMain(), and InitPostgres().

◆ pgstat_bestart()

void pgstat_bestart ( void  )

Definition at line 292 of file backend_status.c.

293 {
294  volatile PgBackendStatus *vbeentry = MyBEEntry;
295  PgBackendStatus lbeentry;
296 #ifdef USE_SSL
297  PgBackendSSLStatus lsslstatus;
298 #endif
299 #ifdef ENABLE_GSS
300  PgBackendGSSStatus lgssstatus;
301 #endif
302 
303  /* pgstats state must be initialized from pgstat_beinit() */
304  Assert(vbeentry != NULL);
305 
306  /*
307  * To minimize the time spent modifying the PgBackendStatus entry, and
308  * avoid risk of errors inside the critical section, we first copy the
309  * shared-memory struct to a local variable, then modify the data in the
310  * local variable, then copy the local variable back to shared memory.
311  * Only the last step has to be inside the critical section.
312  *
313  * Most of the data we copy from shared memory is just going to be
314  * overwritten, but the struct's not so large that it's worth the
315  * maintenance hassle to copy only the needful fields.
316  */
317  memcpy(&lbeentry,
318  unvolatize(PgBackendStatus *, vbeentry),
319  sizeof(PgBackendStatus));
320 
321  /* These structs can just start from zeroes each time, though */
322 #ifdef USE_SSL
323  memset(&lsslstatus, 0, sizeof(lsslstatus));
324 #endif
325 #ifdef ENABLE_GSS
326  memset(&lgssstatus, 0, sizeof(lgssstatus));
327 #endif
328 
329  /*
330  * Now fill in all the fields of lbeentry, except for strings that are
331  * out-of-line data. Those have to be handled separately, below.
332  */
333  lbeentry.st_procpid = MyProcPid;
334  lbeentry.st_backendType = MyBackendType;
336  lbeentry.st_activity_start_timestamp = 0;
337  lbeentry.st_state_start_timestamp = 0;
338  lbeentry.st_xact_start_timestamp = 0;
339  lbeentry.st_databaseid = MyDatabaseId;
340 
341  /* We have userid for client-backends, wal-sender and bgworker processes */
342  if (lbeentry.st_backendType == B_BACKEND
343  || lbeentry.st_backendType == B_WAL_SENDER
344  || lbeentry.st_backendType == B_BG_WORKER)
345  lbeentry.st_userid = GetSessionUserId();
346  else
347  lbeentry.st_userid = InvalidOid;
348 
349  /*
350  * We may not have a MyProcPort (eg, if this is the autovacuum process).
351  * If so, use all-zeroes client address, which is dealt with specially in
352  * pg_stat_get_backend_client_addr and pg_stat_get_backend_client_port.
353  */
354  if (MyProcPort)
355  memcpy(&lbeentry.st_clientaddr, &MyProcPort->raddr,
356  sizeof(lbeentry.st_clientaddr));
357  else
358  MemSet(&lbeentry.st_clientaddr, 0, sizeof(lbeentry.st_clientaddr));
359 
360 #ifdef USE_SSL
362  {
363  lbeentry.st_ssl = true;
370  }
371  else
372  {
373  lbeentry.st_ssl = false;
374  }
375 #else
376  lbeentry.st_ssl = false;
377 #endif
378 
379 #ifdef ENABLE_GSS
380  if (MyProcPort && MyProcPort->gss != NULL)
381  {
382  const char *princ = be_gssapi_get_princ(MyProcPort);
383 
384  lbeentry.st_gss = true;
385  lgssstatus.gss_auth = be_gssapi_get_auth(MyProcPort);
386  lgssstatus.gss_enc = be_gssapi_get_enc(MyProcPort);
388  if (princ)
389  strlcpy(lgssstatus.gss_princ, princ, NAMEDATALEN);
390  }
391  else
392  {
393  lbeentry.st_gss = false;
394  }
395 #else
396  lbeentry.st_gss = false;
397 #endif
398 
399  lbeentry.st_state = STATE_UNDEFINED;
402  lbeentry.st_query_id = UINT64CONST(0);
403 
404  /*
405  * we don't zero st_progress_param here to save cycles; nobody should
406  * examine it until st_progress_command has been set to something other
407  * than PROGRESS_COMMAND_INVALID
408  */
409 
410  /*
411  * We're ready to enter the critical section that fills the shared-memory
412  * status entry. We follow the protocol of bumping st_changecount before
413  * and after; and make sure it's even afterwards. We use a volatile
414  * pointer here to ensure the compiler doesn't try to get cute.
415  */
416  PGSTAT_BEGIN_WRITE_ACTIVITY(vbeentry);
417 
418  /* make sure we'll memcpy the same st_changecount back */
419  lbeentry.st_changecount = vbeentry->st_changecount;
420 
421  memcpy(unvolatize(PgBackendStatus *, vbeentry),
422  &lbeentry,
423  sizeof(PgBackendStatus));
424 
425  /*
426  * We can write the out-of-line strings and structs using the pointers
427  * that are in lbeentry; this saves some de-volatilizing messiness.
428  */
429  lbeentry.st_appname[0] = '\0';
432  NAMEDATALEN);
433  else
434  lbeentry.st_clienthostname[0] = '\0';
435  lbeentry.st_activity_raw[0] = '\0';
436  /* Also make sure the last byte in each string area is always 0 */
437  lbeentry.st_appname[NAMEDATALEN - 1] = '\0';
438  lbeentry.st_clienthostname[NAMEDATALEN - 1] = '\0';
440 
441 #ifdef USE_SSL
442  memcpy(lbeentry.st_sslstatus, &lsslstatus, sizeof(PgBackendSSLStatus));
443 #endif
444 #ifdef ENABLE_GSS
445  memcpy(lbeentry.st_gssstatus, &lgssstatus, sizeof(PgBackendGSSStatus));
446 #endif
447 
448  PGSTAT_END_WRITE_ACTIVITY(vbeentry);
449 
450  /* Update app name to current GUC setting */
451  if (application_name)
453 }
@ PROGRESS_COMMAND_INVALID
void pgstat_report_appname(const char *appname)
#define PGSTAT_END_WRITE_ACTIVITY(beentry)
#define PGSTAT_BEGIN_WRITE_ACTIVITY(beentry)
bool be_gssapi_get_auth(Port *port)
bool be_gssapi_get_enc(Port *port)
const char * be_gssapi_get_princ(Port *port)
bool be_gssapi_get_delegation(Port *port)
const char * be_tls_get_version(Port *port)
int be_tls_get_cipher_bits(Port *port)
void be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
void be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len)
const char * be_tls_get_cipher(Port *port)
void be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len)
#define unvolatize(underlying_type, expr)
Definition: c.h:1257
int MyProcPid
Definition: globals.c:44
TimestampTz MyStartTimestamp
Definition: globals.c:46
struct Port * MyProcPort
Definition: globals.c:47
Oid MyDatabaseId
Definition: globals.c:89
char * application_name
Definition: guc_tables.c:541
@ B_WAL_SENDER
Definition: miscadmin.h:340
@ B_BG_WORKER
Definition: miscadmin.h:333
@ B_BACKEND
Definition: miscadmin.h:332
Oid GetSessionUserId(void)
Definition: miscinit.c:543
BackendType MyBackendType
Definition: miscinit.c:63
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define InvalidOid
Definition: postgres_ext.h:36
char gss_princ[NAMEDATALEN]
char ssl_version[NAMEDATALEN]
char ssl_cipher[NAMEDATALEN]
char ssl_client_dn[NAMEDATALEN]
char ssl_client_serial[NAMEDATALEN]
char ssl_issuer_dn[NAMEDATALEN]
BackendType st_backendType
TimestampTz st_state_start_timestamp
TimestampTz st_proc_start_timestamp
BackendState st_state
TimestampTz st_activity_start_timestamp
ProgressCommandType st_progress_command
SockAddr st_clientaddr
TimestampTz st_xact_start_timestamp
Oid st_progress_command_target
bool ssl_in_use
Definition: libpq-be.h:217
char * remote_hostname
Definition: libpq-be.h:154
void * gss
Definition: libpq-be.h:211
SockAddr raddr
Definition: libpq-be.h:152

References application_name, Assert(), B_BACKEND, B_BG_WORKER, B_WAL_SENDER, be_gssapi_get_auth(), be_gssapi_get_delegation(), be_gssapi_get_enc(), be_gssapi_get_princ(), be_tls_get_cipher(), be_tls_get_cipher_bits(), be_tls_get_peer_issuer_name(), be_tls_get_peer_serial(), be_tls_get_peer_subject_name(), be_tls_get_version(), GetSessionUserId(), Port::gss, PgBackendGSSStatus::gss_auth, PgBackendGSSStatus::gss_delegation, PgBackendGSSStatus::gss_enc, PgBackendGSSStatus::gss_princ, InvalidOid, MemSet, MyBackendType, MyBEEntry, MyDatabaseId, MyProcPid, MyProcPort, MyStartTimestamp, NAMEDATALEN, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, pgstat_report_appname(), pgstat_track_activity_query_size, PROGRESS_COMMAND_INVALID, Port::raddr, Port::remote_hostname, PgBackendSSLStatus::ssl_bits, PgBackendSSLStatus::ssl_cipher, PgBackendSSLStatus::ssl_client_dn, PgBackendSSLStatus::ssl_client_serial, Port::ssl_in_use, PgBackendSSLStatus::ssl_issuer_dn, PgBackendSSLStatus::ssl_version, PgBackendStatus::st_activity_raw, PgBackendStatus::st_activity_start_timestamp, PgBackendStatus::st_appname, PgBackendStatus::st_backendType, PgBackendStatus::st_changecount, PgBackendStatus::st_clientaddr, PgBackendStatus::st_clienthostname, PgBackendStatus::st_databaseid, PgBackendStatus::st_gss, PgBackendStatus::st_gssstatus, PgBackendStatus::st_proc_start_timestamp, PgBackendStatus::st_procpid, PgBackendStatus::st_progress_command, PgBackendStatus::st_progress_command_target, PgBackendStatus::st_query_id, PgBackendStatus::st_ssl, PgBackendStatus::st_sslstatus, PgBackendStatus::st_state, PgBackendStatus::st_state_start_timestamp, PgBackendStatus::st_userid, PgBackendStatus::st_xact_start_timestamp, STATE_UNDEFINED, strlcpy(), and unvolatize.

Referenced by AuxiliaryProcessMain(), and InitPostgres().

◆ pgstat_clear_backend_activity_snapshot()

void pgstat_clear_backend_activity_snapshot ( void  )

Definition at line 486 of file backend_status.c.

487 {
488  /* Release memory, if any was allocated */
490  {
493  }
494 
495  /* Reset variables */
497  localNumBackends = 0;
498 }
static LocalPgBackendStatus * localBackendStatusTable
static int localNumBackends
static MemoryContext backendStatusSnapContext
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403

References backendStatusSnapContext, localBackendStatusTable, localNumBackends, and MemoryContextDelete().

Referenced by pgstat_clear_snapshot().

◆ pgstat_clip_activity()

char* pgstat_clip_activity ( const char *  raw_activity)

Definition at line 1182 of file backend_status.c.

1183 {
1184  char *activity;
1185  int rawlen;
1186  int cliplen;
1187 
1188  /*
1189  * Some callers, like pgstat_get_backend_current_activity(), do not
1190  * guarantee that the buffer isn't concurrently modified. We try to take
1191  * care that the buffer is always terminated by a NUL byte regardless, but
1192  * let's still be paranoid about the string's length. In those cases the
1193  * underlying buffer is guaranteed to be pgstat_track_activity_query_size
1194  * large.
1195  */
1196  activity = pnstrdup(raw_activity, pgstat_track_activity_query_size - 1);
1197 
1198  /* now double-guaranteed to be NUL terminated */
1199  rawlen = strlen(activity);
1200 
1201  /*
1202  * All supported server-encodings make it possible to determine the length
1203  * of a multi-byte character from its first byte (this is not the case for
1204  * client encodings, see GB18030). As st_activity is always stored using
1205  * server encoding, this allows us to perform multi-byte aware truncation,
1206  * even if the string earlier was truncated in the middle of a multi-byte
1207  * character.
1208  */
1209  cliplen = pg_mbcliplen(activity, rawlen,
1211 
1212  activity[cliplen] = '\0';
1213 
1214  return activity;
1215 }
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1084
static int cliplen(const char *str, int len, int limit)
Definition: mbutils.c:1151
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1655

References cliplen(), pg_mbcliplen(), pgstat_track_activity_query_size, and pnstrdup().

Referenced by pg_stat_get_activity(), pg_stat_get_backend_activity(), and pgstat_get_backend_current_activity().

◆ pgstat_fetch_stat_numbackends()

int pgstat_fetch_stat_numbackends ( void  )

Definition at line 1166 of file backend_status.c.

1167 {
1169 
1170  return localNumBackends;
1171 }
static void pgstat_read_current_status(void)

References localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), pg_stat_get_backend_idset(), pg_stat_get_db_numbackends(), and pg_stat_get_progress_info().

◆ pgstat_get_backend_current_activity()

const char* pgstat_get_backend_current_activity ( int  pid,
bool  checkUser 
)

Definition at line 903 of file backend_status.c.

904 {
905  PgBackendStatus *beentry;
906  int i;
907 
908  beentry = BackendStatusArray;
909  for (i = 1; i <= MaxBackends; i++)
910  {
911  /*
912  * Although we expect the target backend's entry to be stable, that
913  * doesn't imply that anyone else's is. To avoid identifying the
914  * wrong backend, while we check for a match to the desired PID we
915  * must follow the protocol of retrying if st_changecount changes
916  * while we examine the entry, or if it's odd. (This might be
917  * unnecessary, since fetching or storing an int is almost certainly
918  * atomic, but let's play it safe.) We use a volatile pointer here to
919  * ensure the compiler doesn't try to get cute.
920  */
921  volatile PgBackendStatus *vbeentry = beentry;
922  bool found;
923 
924  for (;;)
925  {
926  int before_changecount;
927  int after_changecount;
928 
929  pgstat_begin_read_activity(vbeentry, before_changecount);
930 
931  found = (vbeentry->st_procpid == pid);
932 
933  pgstat_end_read_activity(vbeentry, after_changecount);
934 
935  if (pgstat_read_activity_complete(before_changecount,
936  after_changecount))
937  break;
938 
939  /* Make sure we can break out of loop if stuck... */
941  }
942 
943  if (found)
944  {
945  /* Now it is safe to use the non-volatile pointer */
946  if (checkUser && !superuser() && beentry->st_userid != GetUserId())
947  return "<insufficient privilege>";
948  else if (*(beentry->st_activity_raw) == '\0')
949  return "<command string not enabled>";
950  else
951  {
952  /* this'll leak a bit of memory, but that seems acceptable */
953  return pgstat_clip_activity(beentry->st_activity_raw);
954  }
955  }
956 
957  beentry++;
958  }
959 
960  /* If we get here, caller is in error ... */
961  return "<backend information not available>";
962 }
char * pgstat_clip_activity(const char *raw_activity)
#define pgstat_read_activity_complete(before_changecount, after_changecount)
#define pgstat_end_read_activity(beentry, after_changecount)
#define pgstat_begin_read_activity(beentry, before_changecount)
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
Oid GetUserId(void)
Definition: miscinit.c:509
bool superuser(void)
Definition: superuser.c:46

References BackendStatusArray, CHECK_FOR_INTERRUPTS, GetUserId(), i, MaxBackends, pgstat_begin_read_activity, pgstat_clip_activity(), pgstat_end_read_activity, pgstat_read_activity_complete, PgBackendStatus::st_activity_raw, PgBackendStatus::st_procpid, PgBackendStatus::st_userid, and superuser().

Referenced by DeadLockReport().

◆ pgstat_get_beentry_by_backend_id()

◆ pgstat_get_crashed_backend_activity()

const char* pgstat_get_crashed_backend_activity ( int  pid,
char *  buffer,
int  buflen 
)

Definition at line 981 of file backend_status.c.

982 {
983  volatile PgBackendStatus *beentry;
984  int i;
985 
986  beentry = BackendStatusArray;
987 
988  /*
989  * We probably shouldn't get here before shared memory has been set up,
990  * but be safe.
991  */
992  if (beentry == NULL || BackendActivityBuffer == NULL)
993  return NULL;
994 
995  for (i = 1; i <= MaxBackends; i++)
996  {
997  if (beentry->st_procpid == pid)
998  {
999  /* Read pointer just once, so it can't change after validation */
1000  const char *activity = beentry->st_activity_raw;
1001  const char *activity_last;
1002 
1003  /*
1004  * We mustn't access activity string before we verify that it
1005  * falls within the BackendActivityBuffer. To make sure that the
1006  * entire string including its ending is contained within the
1007  * buffer, subtract one activity length from the buffer size.
1008  */
1011 
1012  if (activity < BackendActivityBuffer ||
1013  activity > activity_last)
1014  return NULL;
1015 
1016  /* If no string available, no point in a report */
1017  if (activity[0] == '\0')
1018  return NULL;
1019 
1020  /*
1021  * Copy only ASCII-safe characters so we don't run into encoding
1022  * problems when reporting the message; and be sure not to run off
1023  * the end of memory. As only ASCII characters are reported, it
1024  * doesn't seem necessary to perform multibyte aware clipping.
1025  */
1026  ascii_safe_strlcpy(buffer, activity,
1028 
1029  return buffer;
1030  }
1031 
1032  beentry++;
1033  }
1034 
1035  /* PID not found */
1036  return NULL;
1037 }
void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz)
Definition: ascii.c:174
#define Min(x, y)
Definition: c.h:993

References ascii_safe_strlcpy(), BackendActivityBuffer, BackendActivityBufferSize, BackendStatusArray, i, MaxBackends, Min, pgstat_track_activity_query_size, PgBackendStatus::st_activity_raw, and PgBackendStatus::st_procpid.

Referenced by LogChildExit().

◆ pgstat_get_local_beentry_by_backend_id()

LocalPgBackendStatus* pgstat_get_local_beentry_by_backend_id ( BackendId  beid)

Definition at line 1115 of file backend_status.c.

1116 {
1118 
1120 
1121  /*
1122  * Since the localBackendStatusTable is in order by backend_id, we can use
1123  * bsearch() to search it efficiently.
1124  */
1125  key.backend_id = beid;
1126  return bsearch(&key, localBackendStatusTable, localNumBackends,
1128 }
static int cmp_lbestatus(const void *a, const void *b)

References cmp_lbestatus(), sort-test::key, localBackendStatusTable, localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_backend_subxact(), and pgstat_get_beentry_by_backend_id().

◆ pgstat_get_local_beentry_by_index()

LocalPgBackendStatus* pgstat_get_local_beentry_by_index ( int  idx)

Definition at line 1146 of file backend_status.c.

1147 {
1149 
1150  if (idx < 1 || idx > localNumBackends)
1151  return NULL;
1152 
1153  return &localBackendStatusTable[idx - 1];
1154 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259

References idx(), localBackendStatusTable, localNumBackends, and pgstat_read_current_status().

Referenced by pg_stat_get_activity(), pg_stat_get_backend_idset(), pg_stat_get_db_numbackends(), and pg_stat_get_progress_info().

◆ pgstat_get_my_query_id()

uint64 pgstat_get_my_query_id ( void  )

Definition at line 1045 of file backend_status.c.

1046 {
1047  if (!MyBEEntry)
1048  return 0;
1049 
1050  /*
1051  * There's no need for a lock around pgstat_begin_read_activity /
1052  * pgstat_end_read_activity here as it's only called from
1053  * pg_stat_get_activity which is already protected, or from the same
1054  * backend which means that there won't be concurrent writes.
1055  */
1056  return MyBEEntry->st_query_id;
1057 }

References MyBEEntry, and PgBackendStatus::st_query_id.

Referenced by ExecSerializePlan(), log_status_format(), write_csvlog(), and write_jsonlog().

◆ pgstat_report_activity()

void pgstat_report_activity ( BackendState  state,
const char *  cmd_str 
)

Definition at line 522 of file backend_status.c.

523 {
524  volatile PgBackendStatus *beentry = MyBEEntry;
525  TimestampTz start_timestamp;
526  TimestampTz current_timestamp;
527  int len = 0;
528 
529  TRACE_POSTGRESQL_STATEMENT_STATUS(cmd_str);
530 
531  if (!beentry)
532  return;
533 
535  {
536  if (beentry->st_state != STATE_DISABLED)
537  {
538  volatile PGPROC *proc = MyProc;
539 
540  /*
541  * track_activities is disabled, but we last reported a
542  * non-disabled state. As our final update, change the state and
543  * clear fields we will not be updating anymore.
544  */
546  beentry->st_state = STATE_DISABLED;
547  beentry->st_state_start_timestamp = 0;
548  beentry->st_activity_raw[0] = '\0';
549  beentry->st_activity_start_timestamp = 0;
550  /* st_xact_start_timestamp and wait_event_info are also disabled */
551  beentry->st_xact_start_timestamp = 0;
552  beentry->st_query_id = UINT64CONST(0);
553  proc->wait_event_info = 0;
554  PGSTAT_END_WRITE_ACTIVITY(beentry);
555  }
556  return;
557  }
558 
559  /*
560  * To minimize the time spent modifying the entry, and avoid risk of
561  * errors inside the critical section, fetch all the needed data first.
562  */
563  start_timestamp = GetCurrentStatementStartTimestamp();
564  if (cmd_str != NULL)
565  {
566  /*
567  * Compute length of to-be-stored string unaware of multi-byte
568  * characters. For speed reasons that'll get corrected on read, rather
569  * than computed every write.
570  */
571  len = Min(strlen(cmd_str), pgstat_track_activity_query_size - 1);
572  }
573  current_timestamp = GetCurrentTimestamp();
574 
575  /*
576  * If the state has changed from "active" or "idle in transaction",
577  * calculate the duration.
578  */
579  if ((beentry->st_state == STATE_RUNNING ||
580  beentry->st_state == STATE_FASTPATH ||
581  beentry->st_state == STATE_IDLEINTRANSACTION ||
583  state != beentry->st_state)
584  {
585  long secs;
586  int usecs;
587 
589  current_timestamp,
590  &secs, &usecs);
591 
592  if (beentry->st_state == STATE_RUNNING ||
593  beentry->st_state == STATE_FASTPATH)
594  pgstat_count_conn_active_time((PgStat_Counter) secs * 1000000 + usecs);
595  else
596  pgstat_count_conn_txn_idle_time((PgStat_Counter) secs * 1000000 + usecs);
597  }
598 
599  /*
600  * Now update the status entry
601  */
603 
604  beentry->st_state = state;
605  beentry->st_state_start_timestamp = current_timestamp;
606 
607  /*
608  * If a new query is started, we reset the query identifier as it'll only
609  * be known after parse analysis, to avoid reporting last query's
610  * identifier.
611  */
612  if (state == STATE_RUNNING)
613  beentry->st_query_id = UINT64CONST(0);
614 
615  if (cmd_str != NULL)
616  {
617  memcpy((char *) beentry->st_activity_raw, cmd_str, len);
618  beentry->st_activity_raw[len] = '\0';
619  beentry->st_activity_start_timestamp = start_timestamp;
620  }
621 
622  PGSTAT_END_WRITE_ACTIVITY(beentry);
623 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1659
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
bool pgstat_track_activities
int64 TimestampTz
Definition: timestamp.h:39
const void size_t len
#define pgstat_count_conn_txn_idle_time(n)
Definition: pgstat.h:556
#define pgstat_count_conn_active_time(n)
Definition: pgstat.h:554
int64 PgStat_Counter
Definition: pgstat.h:89
PGPROC * MyProc
Definition: proc.c:66
Definition: proc.h:162
uint32 wait_event_info
Definition: proc.h:270
Definition: regguts.h:323
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:864

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), len, Min, MyBEEntry, MyProc, PGSTAT_BEGIN_WRITE_ACTIVITY, pgstat_count_conn_active_time, pgstat_count_conn_txn_idle_time, PGSTAT_END_WRITE_ACTIVITY, pgstat_track_activities, pgstat_track_activity_query_size, PgBackendStatus::st_activity_raw, PgBackendStatus::st_activity_start_timestamp, PgBackendStatus::st_query_id, PgBackendStatus::st_state, PgBackendStatus::st_state_start_timestamp, PgBackendStatus::st_xact_start_timestamp, STATE_DISABLED, STATE_FASTPATH, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, STATE_RUNNING, TimestampDifference(), and PGPROC::wait_event_info.

Referenced by _bt_parallel_build_main(), apply_handle_begin(), apply_handle_begin_prepare(), apply_handle_commit(), apply_handle_commit_prepared(), apply_handle_prepare(), apply_handle_rollback_prepared(), apply_handle_stream_commit(), apply_handle_stream_prepare(), apply_handle_stream_start(), apply_handle_stream_stop(), apply_spooled_messages(), autovac_report_activity(), autovac_report_workitem(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), initialize_worker_spi(), LogicalRepApplyLoop(), pa_stream_abort(), parallel_vacuum_main(), ParallelQueryMain(), PostgresMain(), and worker_spi_main().

◆ pgstat_report_appname()

void pgstat_report_appname ( const char *  appname)

Definition at line 672 of file backend_status.c.

673 {
674  volatile PgBackendStatus *beentry = MyBEEntry;
675  int len;
676 
677  if (!beentry)
678  return;
679 
680  /* This should be unnecessary if GUC did its job, but be safe */
681  len = pg_mbcliplen(appname, strlen(appname), NAMEDATALEN - 1);
682 
683  /*
684  * Update my status entry, following the protocol of bumping
685  * st_changecount before and after. We use a volatile pointer here to
686  * ensure the compiler doesn't try to get cute.
687  */
689 
690  memcpy((char *) beentry->st_appname, appname, len);
691  beentry->st_appname[len] = '\0';
692 
693  PGSTAT_END_WRITE_ACTIVITY(beentry);
694 }

References len, MyBEEntry, NAMEDATALEN, pg_mbcliplen(), PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, and PgBackendStatus::st_appname.

Referenced by assign_application_name(), and pgstat_bestart().

◆ pgstat_report_query_id()

void pgstat_report_query_id ( uint64  query_id,
bool  force 
)

Definition at line 632 of file backend_status.c.

633 {
634  volatile PgBackendStatus *beentry = MyBEEntry;
635 
636  /*
637  * if track_activities is disabled, st_query_id should already have been
638  * reset
639  */
640  if (!beentry || !pgstat_track_activities)
641  return;
642 
643  /*
644  * We only report the top-level query identifiers. The stored query_id is
645  * reset when a backend calls pgstat_report_activity(STATE_RUNNING), or
646  * with an explicit call to this function using the force flag. If the
647  * saved query identifier is not zero it means that it's not a top-level
648  * command, so ignore the one provided unless it's an explicit call to
649  * reset the identifier.
650  */
651  if (beentry->st_query_id != 0 && !force)
652  return;
653 
654  /*
655  * Update my status entry, following the protocol of bumping
656  * st_changecount before and after. We use a volatile pointer here to
657  * ensure the compiler doesn't try to get cute.
658  */
660  beentry->st_query_id = query_id;
661  PGSTAT_END_WRITE_ACTIVITY(beentry);
662 }

References MyBEEntry, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, pgstat_track_activities, and PgBackendStatus::st_query_id.

Referenced by exec_simple_query(), ExecutorStart(), parse_analyze_fixedparams(), parse_analyze_varparams(), and parse_analyze_withcb().

◆ pgstat_report_tempfile()

void pgstat_report_tempfile ( size_t  filesize)

Definition at line 175 of file pgstat_database.c.

176 {
177  PgStat_StatDBEntry *dbent;
178 
179  if (!pgstat_track_counts)
180  return;
181 
183  dbent->temp_bytes += filesize;
184  dbent->temp_files++;
185 }
bool pgstat_track_counts
Definition: pgstat.c:187
PgStat_StatDBEntry * pgstat_prep_database_pending(Oid dboid)
PgStat_Counter temp_bytes
Definition: pgstat.h:340
PgStat_Counter temp_files
Definition: pgstat.h:339

References MyDatabaseId, pgstat_prep_database_pending(), pgstat_track_counts, PgStat_StatDBEntry::temp_bytes, and PgStat_StatDBEntry::temp_files.

Referenced by ReportTemporaryFileUsage().

◆ pgstat_report_xact_timestamp()

void pgstat_report_xact_timestamp ( TimestampTz  tstamp)

Definition at line 701 of file backend_status.c.

702 {
703  volatile PgBackendStatus *beentry = MyBEEntry;
704 
705  if (!pgstat_track_activities || !beentry)
706  return;
707 
708  /*
709  * Update my status entry, following the protocol of bumping
710  * st_changecount before and after. We use a volatile pointer here to
711  * ensure the compiler doesn't try to get cute.
712  */
714 
715  beentry->st_xact_start_timestamp = tstamp;
716 
717  PGSTAT_END_WRITE_ACTIVITY(beentry);
718 }

References MyBEEntry, PGSTAT_BEGIN_WRITE_ACTIVITY, PGSTAT_END_WRITE_ACTIVITY, pgstat_track_activities, and PgBackendStatus::st_xact_start_timestamp.

Referenced by AbortTransaction(), CommitTransaction(), PrepareTransaction(), and StartTransaction().

Variable Documentation

◆ MyBEEntry

◆ pgstat_track_activities

◆ pgstat_track_activity_query_size