PostgreSQL Source Code  git master
mcxtfuncs.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * mcxtfuncs.c
4  * Functions to show backend memory context.
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/utils/adt/mcxtfuncs.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include "funcapi.h"
19 #include "miscadmin.h"
20 #include "mb/pg_wchar.h"
21 #include "storage/proc.h"
22 #include "storage/procarray.h"
23 #include "utils/builtins.h"
24 
25 /* ----------
26  * The max bytes for showing identifiers of MemoryContext.
27  * ----------
28  */
29 #define MEMORY_CONTEXT_IDENT_DISPLAY_SIZE 1024
30 
31 /*
32  * PutMemoryContextsStatsTupleStore
33  * One recursion level for pg_get_backend_memory_contexts.
34  */
35 static void
37  TupleDesc tupdesc, MemoryContext context,
38  const char *parent, int level)
39 {
40 #define PG_GET_BACKEND_MEMORY_CONTEXTS_COLS 9
41 
45  MemoryContext child;
46  const char *name;
47  const char *ident;
48 
50 
51  name = context->name;
52  ident = context->ident;
53 
54  /*
55  * To be consistent with logging output, we label dynahash contexts with
56  * just the hash table name as with MemoryContextStatsPrint().
57  */
58  if (ident && strcmp(name, "dynahash") == 0)
59  {
60  name = ident;
61  ident = NULL;
62  }
63 
64  /* Examine the context itself */
65  memset(&stat, 0, sizeof(stat));
66  (*context->methods->stats) (context, NULL, (void *) &level, &stat, true);
67 
68  memset(values, 0, sizeof(values));
69  memset(nulls, 0, sizeof(nulls));
70 
71  if (name)
72  values[0] = CStringGetTextDatum(name);
73  else
74  nulls[0] = true;
75 
76  if (ident)
77  {
78  int idlen = strlen(ident);
79  char clipped_ident[MEMORY_CONTEXT_IDENT_DISPLAY_SIZE];
80 
81  /*
82  * Some identifiers such as SQL query string can be very long,
83  * truncate oversize identifiers.
84  */
86  idlen = pg_mbcliplen(ident, idlen, MEMORY_CONTEXT_IDENT_DISPLAY_SIZE - 1);
87 
88  memcpy(clipped_ident, ident, idlen);
89  clipped_ident[idlen] = '\0';
90  values[1] = CStringGetTextDatum(clipped_ident);
91  }
92  else
93  nulls[1] = true;
94 
95  if (parent)
96  values[2] = CStringGetTextDatum(parent);
97  else
98  nulls[2] = true;
99 
100  values[3] = Int32GetDatum(level);
101  values[4] = Int64GetDatum(stat.totalspace);
102  values[5] = Int64GetDatum(stat.nblocks);
103  values[6] = Int64GetDatum(stat.freespace);
104  values[7] = Int64GetDatum(stat.freechunks);
105  values[8] = Int64GetDatum(stat.totalspace - stat.freespace);
106  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
107 
108  for (child = context->firstchild; child != NULL; child = child->nextchild)
109  {
110  PutMemoryContextsStatsTupleStore(tupstore, tupdesc,
111  child, name, level + 1);
112  }
113 }
114 
115 /*
116  * pg_get_backend_memory_contexts
117  * SQL SRF showing backend memory context.
118  */
119 Datum
121 {
122  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
123  TupleDesc tupdesc;
124  Tuplestorestate *tupstore;
125  MemoryContext per_query_ctx;
126  MemoryContext oldcontext;
127 
128  /* check to see if caller supports us returning a tuplestore */
129  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
130  ereport(ERROR,
131  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
132  errmsg("set-valued function called in context that cannot accept a set")));
133  if (!(rsinfo->allowedModes & SFRM_Materialize))
134  ereport(ERROR,
135  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
136  errmsg("materialize mode required, but it is not allowed in this context")));
137 
138  /* Build a tuple descriptor for our result type */
139  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
140  elog(ERROR, "return type must be a row type");
141 
142  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
143  oldcontext = MemoryContextSwitchTo(per_query_ctx);
144 
145  tupstore = tuplestore_begin_heap(true, false, work_mem);
146  rsinfo->returnMode = SFRM_Materialize;
147  rsinfo->setResult = tupstore;
148  rsinfo->setDesc = tupdesc;
149 
150  MemoryContextSwitchTo(oldcontext);
151 
152  PutMemoryContextsStatsTupleStore(tupstore, tupdesc,
153  TopMemoryContext, NULL, 0);
154 
155  /* clean up and return the tuplestore */
156  tuplestore_donestoring(tupstore);
157 
158  return (Datum) 0;
159 }
160 
161 /*
162  * pg_log_backend_memory_contexts
163  * Signal a backend process to log its memory contexts.
164  *
165  * Only superusers are allowed to signal to log the memory contexts
166  * because allowing any users to issue this request at an unbounded
167  * rate would cause lots of log messages and which can lead to
168  * denial of service.
169  *
170  * On receipt of this signal, a backend sets the flag in the signal
171  * handler, which causes the next CHECK_FOR_INTERRUPTS() to log the
172  * memory contexts.
173  */
174 Datum
176 {
177  int pid = PG_GETARG_INT32(0);
178  PGPROC *proc;
179 
180  /* Only allow superusers to log memory contexts. */
181  if (!superuser())
182  ereport(ERROR,
183  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
184  errmsg("must be a superuser to log memory contexts")));
185 
186  proc = BackendPidGetProc(pid);
187 
188  /*
189  * BackendPidGetProc returns NULL if the pid isn't valid; but by the time
190  * we reach kill(), a process for which we get a valid proc here might
191  * have terminated on its own. There's no way to acquire a lock on an
192  * arbitrary process to prevent that. But since this mechanism is usually
193  * used to debug a backend running and consuming lots of memory, that it
194  * might end on its own first and its memory contexts are not logged is
195  * not a problem.
196  */
197  if (proc == NULL)
198  {
199  /*
200  * This is just a warning so a loop-through-resultset will not abort
201  * if one backend terminated on its own during the run.
202  */
204  (errmsg("PID %d is not a PostgreSQL server process", pid)));
205  PG_RETURN_BOOL(false);
206  }
207 
209  {
210  /* Again, just a warning to allow loops */
212  (errmsg("could not send signal to process %d: %m", pid)));
213  PG_RETURN_BOOL(false);
214  }
215 
216  PG_RETURN_BOOL(true);
217 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
void(* stats)(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr)
Definition: memnodes.h:68
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:207
BackendId backendId
Definition: proc.h:153
const MemoryContextMethods * methods
Definition: memnodes.h:85
Datum pg_log_backend_memory_contexts(PG_FUNCTION_ARGS)
Definition: mcxtfuncs.c:175
PGPROC * BackendPidGetProc(int pid)
Definition: procarray.c:3133
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
static void PutMemoryContextsStatsTupleStore(Tuplestorestate *tupstore, TupleDesc tupdesc, MemoryContext context, const char *parent, int level)
Definition: mcxtfuncs.c:36
int SendProcSignal(pid_t pid, ProcSignalReason reason, BackendId backendId)
Definition: procsignal.c:261
MemoryContext firstchild
Definition: memnodes.h:87
#define PG_GET_BACKEND_MEMORY_CONTEXTS_COLS
#define ERROR
Definition: elog.h:46
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1026
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1697
#define AssertArg(condition)
Definition: c.h:806
const char * ident
Definition: memnodes.h:91
MemoryContext TopMemoryContext
Definition: mcxt.c:48
#define WARNING
Definition: elog.h:40
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
uintptr_t Datum
Definition: postgres.h:411
int work_mem
Definition: globals.c:124
#define ereport(elevel,...)
Definition: elog.h:157
int allowedModes
Definition: execnodes.h:305
SetFunctionReturnMode returnMode
Definition: execnodes.h:307
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
Datum pg_get_backend_memory_contexts(PG_FUNCTION_ARGS)
Definition: mcxtfuncs.c:120
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:233
const char * name
Definition: encode.c:515
Tuplestorestate * setResult
Definition: execnodes.h:310
static Datum values[MAXATTR]
Definition: bootstrap.c:166
ExprContext * econtext
Definition: execnodes.h:303
#define Int32GetDatum(X)
Definition: postgres.h:523
TupleDesc setDesc
Definition: execnodes.h:311
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define CStringGetTextDatum(s)
Definition: builtins.h:82
#define MEMORY_CONTEXT_IDENT_DISPLAY_SIZE
Definition: mcxtfuncs.c:29
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
Definition: proc.h:121
const char * name
Definition: memnodes.h:90
MemoryContext nextchild
Definition: memnodes.h:89
#define stat
Definition: win32_port.h:275