Commit 0423de4d authored by Magnus Hagander's avatar Magnus Hagander

Make the pg_stat_activity view call a SRF (pg_stat_get_activity())

instead of calling a bunch of individual functions.

This function can also be called directly, taking a PID as an argument, to
return only the data for a single PID.
parent 8008988b
<!-- $PostgreSQL: pgsql/doc/src/sgml/monitoring.sgml,v 1.57 2008/04/10 13:34:33 alvherre Exp $ -->
<!-- $PostgreSQL: pgsql/doc/src/sgml/monitoring.sgml,v 1.58 2008/05/07 14:41:55 mha Exp $ -->
<chapter id="monitoring">
<title>Monitoring Database Activity</title>
......@@ -655,20 +655,31 @@ postgres: <replaceable>user</> <replaceable>database</> <replaceable>host</> <re
</row>
<row>
<entry><literal><function>pg_stat_get_backend_idset</function>()</literal></entry>
<entry><type>setof integer</type></entry>
<!-- See also the entry for this in func.sgml -->
<entry><literal><function>pg_backend_pid</function>()</literal></entry>
<entry><type>integer</type></entry>
<entry>
Set of currently active server process numbers (from 1 to the
number of active server processes). See usage example in the text
Process ID of the server process attached to the current session
</entry>
</row>
<row>
<!-- See also the entry for this in func.sgml -->
<entry><literal><function>pg_backend_pid</function>()</literal></entry>
<entry><type>integer</type></entry>
<entry><literal><function>pg_stat_get_activity</function>(<type>integer</type>)</literal></entry>
<entry><type>setof record</type></entry>
<entry>
Process ID of the server process attached to the current session
Returns a record of information about the backend with the specified pid, or
one record for each active backend in the system if <symbol>NULL</symbol> is
specified. The fields returned are the same as in the
<structname>pg_stat_activity</structname> view
</entry>
</row>
<row>
<entry><literal><function>pg_stat_get_backend_idset</function>()</literal></entry>
<entry><type>setof integer</type></entry>
<entry>
Set of currently active server process numbers (from 1 to the
number of active server processes). See usage example in the text
</entry>
</row>
......@@ -869,6 +880,8 @@ postgres: <replaceable>user</> <replaceable>database</> <replaceable>host</> <re
</note>
<para>
All functions to access information about backends are indexed by backend id
number, except <function>pg_stat_get_activity</function> which is indexed by PID.
The function <function>pg_stat_get_backend_idset</function> provides
a convenient way to generate one row for each active server process. For
example, to show the <acronym>PID</>s and current queries of all server processes:
......
......@@ -3,7 +3,7 @@
*
* Copyright (c) 1996-2008, PostgreSQL Global Development Group
*
* $PostgreSQL: pgsql/src/backend/catalog/system_views.sql,v 1.49 2008/03/10 12:55:13 mha Exp $
* $PostgreSQL: pgsql/src/backend/catalog/system_views.sql,v 1.50 2008/05/07 14:41:55 mha Exp $
*/
CREATE VIEW pg_roles AS
......@@ -341,23 +341,26 @@ CREATE VIEW pg_statio_user_sequences AS
CREATE VIEW pg_stat_activity AS
SELECT
D.oid AS datid,
D.datname AS datname,
pg_stat_get_backend_pid(S.backendid) AS procpid,
pg_stat_get_backend_userid(S.backendid) AS usesysid,
U.rolname AS usename,
pg_stat_get_backend_activity(S.backendid) AS current_query,
pg_stat_get_backend_waiting(S.backendid) AS waiting,
pg_stat_get_backend_xact_start(S.backendid) AS xact_start,
pg_stat_get_backend_activity_start(S.backendid) AS query_start,
pg_stat_get_backend_start(S.backendid) AS backend_start,
pg_stat_get_backend_client_addr(S.backendid) AS client_addr,
pg_stat_get_backend_client_port(S.backendid) AS client_port
S.datid AS datid,
D.datname AS datname,
S.procpid,
S.usesysid,
U.rolname AS usename,
S.current_query,
S.waiting,
S.xact_start,
S.query_start,
S.backend_start,
S.client_addr,
S.client_port
FROM pg_database D,
(SELECT pg_stat_get_backend_idset() AS backendid) AS S,
pg_stat_get_activity(NULL) AS S(datid oid, procpid int,
usesysid oid, current_query text, waiting boolean,
xact_start timestamptz, query_start timestamptz,
backend_start timestamptz, client_addr inet, client_port int),
pg_authid U
WHERE pg_stat_get_backend_dbid(S.backendid) = D.oid AND
pg_stat_get_backend_userid(S.backendid) = U.oid;
WHERE S.datid = D.oid AND
S.usesysid = U.oid;
CREATE VIEW pg_stat_database AS
SELECT
......
......@@ -8,7 +8,7 @@
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/utils/adt/pgstatfuncs.c,v 1.49 2008/03/25 22:42:44 tgl Exp $
* $PostgreSQL: pgsql/src/backend/utils/adt/pgstatfuncs.c,v 1.50 2008/05/07 14:41:55 mha Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -17,6 +17,8 @@
#include "funcapi.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "catalog/pg_type.h"
#include "access/heapam.h"
#include "utils/builtins.h"
#include "utils/inet.h"
#include "libpq/ip.h"
......@@ -39,6 +41,7 @@ extern Datum pg_stat_get_last_analyze_time(PG_FUNCTION_ARGS);
extern Datum pg_stat_get_last_autoanalyze_time(PG_FUNCTION_ARGS);
extern Datum pg_stat_get_backend_idset(PG_FUNCTION_ARGS);
extern Datum pg_stat_get_activity(PG_FUNCTION_ARGS);
extern Datum pg_backend_pid(PG_FUNCTION_ARGS);
extern Datum pg_stat_get_backend_pid(PG_FUNCTION_ARGS);
extern Datum pg_stat_get_backend_dbid(PG_FUNCTION_ARGS);
......@@ -363,6 +366,225 @@ pg_stat_get_backend_idset(PG_FUNCTION_ARGS)
}
}
Datum
pg_stat_get_activity(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
TupleDesc tupdesc;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
tupdesc = CreateTemplateTupleDesc(10, false);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "datid", OIDOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "procpid", INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 3, "usesysid", OIDOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 4, "current_query", TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 5, "waiting", BOOLOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 6, "act_start", TIMESTAMPTZOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 7, "query_start", TIMESTAMPTZOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 8, "backend_start", TIMESTAMPTZOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 9, "client_addr", INETOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 10, "client_port", INT4OID, -1, 0);
funcctx->tuple_desc = BlessTupleDesc(tupdesc);
funcctx->user_fctx = palloc0(sizeof(int));
if (PG_ARGISNULL(0))
{
/* Get all backends */
funcctx->max_calls = pgstat_fetch_stat_numbackends();
}
else
{
/*
* Get one backend - locate by pid.
*
* We lookup the backend early, so we can return zero rows if it doesn't
* exist, instead of returning a single row full of NULLs.
*/
int pid = PG_GETARG_INT32(0);
int i;
int n = pgstat_fetch_stat_numbackends();
for (i = 1; i <= n; i++)
{
PgBackendStatus *be = pgstat_fetch_stat_beentry(i);
if (be)
{
if (be->st_procpid == pid)
{
*(int *)(funcctx->user_fctx) = i;
break;
}
}
}
if (*(int *)(funcctx->user_fctx) == 0)
/* Pid not found, return zero rows */
funcctx->max_calls = 0;
else
funcctx->max_calls = 1;
}
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
if (funcctx->call_cntr < funcctx->max_calls)
{
/* for each row */
Datum values[10];
bool nulls[10];
HeapTuple tuple;
PgBackendStatus *beentry;
SockAddr zero_clientaddr;
MemSet(values, 0, sizeof(values));
MemSet(nulls, 0, sizeof(nulls));
if (*(int *)(funcctx->user_fctx) > 0)
/* Get specific pid slot */
beentry = pgstat_fetch_stat_beentry(*(int *)(funcctx->user_fctx));
else
/* Get the next one in the list */
beentry = pgstat_fetch_stat_beentry(funcctx->call_cntr+1); /* 1-based index */
if (!beentry)
{
int i;
for (i = 0; i < sizeof(nulls)/sizeof(nulls[0]); i++)
nulls[i] = true;
nulls[3] = false;
values[3] = CStringGetTextDatum("<backend information not available>");
tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
}
/* Values available to all callers */
values[0] = ObjectIdGetDatum(beentry->st_databaseid);
values[1] = Int32GetDatum(beentry->st_procpid);
values[2] = ObjectIdGetDatum(beentry->st_userid);
/* Values only available to same user or superuser */
if (superuser() || beentry->st_userid == GetUserId())
{
if (*(beentry->st_activity) == '\0')
{
values[3] = CStringGetTextDatum("<command string not enabled>");
}
else
{
values[3] = CStringGetTextDatum(beentry->st_activity);
}
values[4] = BoolGetDatum(beentry->st_waiting);
if (beentry->st_xact_start_timestamp != 0)
values[5] = TimestampTzGetDatum(beentry->st_xact_start_timestamp);
else
nulls[5] = true;
if (beentry->st_activity_start_timestamp != 0)
values[6] = TimestampTzGetDatum(beentry->st_activity_start_timestamp);
else
nulls[6] = true;
if (beentry->st_proc_start_timestamp != 0)
values[7] = TimestampTzGetDatum(beentry->st_proc_start_timestamp);
else
nulls[7] = true;
/* A zeroed client addr means we don't know */
memset(&zero_clientaddr, 0, sizeof(zero_clientaddr));
if (memcmp(&(beentry->st_clientaddr), &zero_clientaddr,
sizeof(zero_clientaddr) == 0))
{
nulls[8] = true;
nulls[9] = true;
}
else
{
if (beentry->st_clientaddr.addr.ss_family == AF_INET
#ifdef HAVE_IPV6
|| beentry->st_clientaddr.addr.ss_family == AF_INET6
#endif
)
{
char remote_host[NI_MAXHOST];
char remote_port[NI_MAXSERV];
int ret;
remote_host[0] = '\0';
remote_port[0] = '\0';
ret = pg_getnameinfo_all(&beentry->st_clientaddr.addr,
beentry->st_clientaddr.salen,
remote_host, sizeof(remote_host),
remote_port, sizeof(remote_port),
NI_NUMERICHOST | NI_NUMERICSERV);
if (ret)
{
nulls[8] = true;
nulls[9] = true;
}
else
{
clean_ipv6_addr(beentry->st_clientaddr.addr.ss_family, remote_host);
values[8] = DirectFunctionCall1(inet_in,
CStringGetDatum(remote_host));
values[9] = Int32GetDatum(atoi(remote_port));
}
}
else if (beentry->st_clientaddr.addr.ss_family == AF_UNIX)
{
/*
* Unix sockets always reports NULL for host and -1 for port, so it's
* possible to tell the difference to connections we have no
* permissions to view, or with errors.
*/
nulls[8] = true;
values[9] = DatumGetInt32(-1);
}
else
{
/* Unknown address type, should never happen */
nulls[8] = true;
nulls[9] = true;
}
}
}
else
{
/* No permissions to view data about this session */
values[3] = CStringGetTextDatum("<insufficient privilege>");
nulls[4] = true;
nulls[5] = true;
nulls[6] = true;
nulls[7] = true;
nulls[8] = true;
nulls[9] = true;
}
tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
}
else
{
/* nothing left */
SRF_RETURN_DONE(funcctx);
}
}
Datum
pg_backend_pid(PG_FUNCTION_ARGS)
......
......@@ -37,7 +37,7 @@
* Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/catalog/catversion.h,v 1.455 2008/05/04 23:19:23 tgl Exp $
* $PostgreSQL: pgsql/src/include/catalog/catversion.h,v 1.456 2008/05/07 14:41:55 mha Exp $
*
*-------------------------------------------------------------------------
*/
......@@ -53,6 +53,6 @@
*/
/* yyyymmddN */
#define CATALOG_VERSION_NO 200805042
#define CATALOG_VERSION_NO 200805071
#endif
......@@ -7,7 +7,7 @@
* Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* $PostgreSQL: pgsql/src/include/catalog/pg_proc.h,v 1.496 2008/05/04 23:19:23 tgl Exp $
* $PostgreSQL: pgsql/src/include/catalog/pg_proc.h,v 1.497 2008/05/07 14:41:55 mha Exp $
*
* NOTES
* The script catalog/genbki.sh reads this file and generates .bki
......@@ -2904,6 +2904,8 @@ DATA(insert OID = 2784 ( pg_stat_get_last_autoanalyze_time PGNSP PGUID 12 1 0 f
DESCR("statistics: last auto analyze time for a table");
DATA(insert OID = 1936 ( pg_stat_get_backend_idset PGNSP PGUID 12 1 100 f f t t s 0 23 "" _null_ _null_ _null_ pg_stat_get_backend_idset - _null_ _null_ ));
DESCR("statistics: currently active backend IDs");
DATA(insert OID = 2022 ( pg_stat_get_activity PGNSP PGUID 12 1 100 f f f t s 1 2249 "23" _null_ _null_ _null_ pg_stat_get_activity - _null_ _null_ ));
DESCR("statistics: information about currently active backends");
DATA(insert OID = 2026 ( pg_backend_pid PGNSP PGUID 12 1 0 f f t f s 0 23 "" _null_ _null_ _null_ pg_backend_pid - _null_ _null_ ));
DESCR("statistics: current backend PID");
DATA(insert OID = 1937 ( pg_stat_get_backend_pid PGNSP PGUID 12 1 0 f f t f s 1 23 "23" _null_ _null_ _null_ pg_stat_get_backend_pid - _null_ _null_ ));
......
......@@ -1289,7 +1289,7 @@ SELECT viewname, definition FROM pg_views WHERE schemaname <> 'information_schem
pg_rules | SELECT n.nspname AS schemaname, c.relname AS tablename, r.rulename, pg_get_ruledef(r.oid) AS definition FROM ((pg_rewrite r JOIN pg_class c ON ((c.oid = r.ev_class))) LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (r.rulename <> '_RETURN'::name);
pg_settings | SELECT a.name, a.setting, a.unit, a.category, a.short_desc, a.extra_desc, a.context, a.vartype, a.source, a.min_val, a.max_val, a.enumvals FROM pg_show_all_settings() a(name text, setting text, unit text, category text, short_desc text, extra_desc text, context text, vartype text, source text, min_val text, max_val text, enumvals text);
pg_shadow | SELECT pg_authid.rolname AS usename, pg_authid.oid AS usesysid, pg_authid.rolcreatedb AS usecreatedb, pg_authid.rolsuper AS usesuper, pg_authid.rolcatupdate AS usecatupd, pg_authid.rolpassword AS passwd, (pg_authid.rolvaliduntil)::abstime AS valuntil, pg_authid.rolconfig AS useconfig FROM pg_authid WHERE pg_authid.rolcanlogin;
pg_stat_activity | SELECT d.oid AS datid, d.datname, pg_stat_get_backend_pid(s.backendid) AS procpid, pg_stat_get_backend_userid(s.backendid) AS usesysid, u.rolname AS usename, pg_stat_get_backend_activity(s.backendid) AS current_query, pg_stat_get_backend_waiting(s.backendid) AS waiting, pg_stat_get_backend_xact_start(s.backendid) AS xact_start, pg_stat_get_backend_activity_start(s.backendid) AS query_start, pg_stat_get_backend_start(s.backendid) AS backend_start, pg_stat_get_backend_client_addr(s.backendid) AS client_addr, pg_stat_get_backend_client_port(s.backendid) AS client_port FROM pg_database d, (SELECT pg_stat_get_backend_idset() AS backendid) s, pg_authid u WHERE ((pg_stat_get_backend_dbid(s.backendid) = d.oid) AND (pg_stat_get_backend_userid(s.backendid) = u.oid));
pg_stat_activity | SELECT s.datid, d.datname, s.procpid, s.usesysid, u.rolname AS usename, s.current_query, s.waiting, s.xact_start, s.query_start, s.backend_start, s.client_addr, s.client_port FROM pg_database d, pg_stat_get_activity(NULL::integer) s(datid oid, procpid integer, usesysid oid, current_query text, waiting boolean, xact_start timestamp with time zone, query_start timestamp with time zone, backend_start timestamp with time zone, client_addr inet, client_port integer), pg_authid u WHERE ((s.datid = d.oid) AND (s.usesysid = u.oid));
pg_stat_all_indexes | SELECT c.oid AS relid, i.oid AS indexrelid, n.nspname AS schemaname, c.relname, i.relname AS indexrelname, pg_stat_get_numscans(i.oid) AS idx_scan, pg_stat_get_tuples_returned(i.oid) AS idx_tup_read, pg_stat_get_tuples_fetched(i.oid) AS idx_tup_fetch FROM (((pg_class c JOIN pg_index x ON ((c.oid = x.indrelid))) JOIN pg_class i ON ((i.oid = x.indexrelid))) LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = ANY (ARRAY['r'::"char", 't'::"char"]));
pg_stat_all_tables | SELECT c.oid AS relid, n.nspname AS schemaname, c.relname, pg_stat_get_numscans(c.oid) AS seq_scan, pg_stat_get_tuples_returned(c.oid) AS seq_tup_read, (sum(pg_stat_get_numscans(i.indexrelid)))::bigint AS idx_scan, ((sum(pg_stat_get_tuples_fetched(i.indexrelid)))::bigint + pg_stat_get_tuples_fetched(c.oid)) AS idx_tup_fetch, pg_stat_get_tuples_inserted(c.oid) AS n_tup_ins, pg_stat_get_tuples_updated(c.oid) AS n_tup_upd, pg_stat_get_tuples_deleted(c.oid) AS n_tup_del, pg_stat_get_tuples_hot_updated(c.oid) AS n_tup_hot_upd, pg_stat_get_live_tuples(c.oid) AS n_live_tup, pg_stat_get_dead_tuples(c.oid) AS n_dead_tup, pg_stat_get_last_vacuum_time(c.oid) AS last_vacuum, pg_stat_get_last_autovacuum_time(c.oid) AS last_autovacuum, pg_stat_get_last_analyze_time(c.oid) AS last_analyze, pg_stat_get_last_autoanalyze_time(c.oid) AS last_autoanalyze FROM ((pg_class c LEFT JOIN pg_index i ON ((c.oid = i.indrelid))) LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) WHERE (c.relkind = ANY (ARRAY['r'::"char", 't'::"char"])) GROUP BY c.oid, n.nspname, c.relname;
pg_stat_bgwriter | SELECT pg_stat_get_bgwriter_timed_checkpoints() AS checkpoints_timed, pg_stat_get_bgwriter_requested_checkpoints() AS checkpoints_req, pg_stat_get_bgwriter_buf_written_checkpoints() AS buffers_checkpoint, pg_stat_get_bgwriter_buf_written_clean() AS buffers_clean, pg_stat_get_bgwriter_maxwritten_clean() AS maxwritten_clean, pg_stat_get_buf_written_backend() AS buffers_backend, pg_stat_get_buf_alloc() AS buffers_alloc;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment