From f1f7e2cf538a29084964788cbff77468eab438e4 Mon Sep 17 00:00:00 2001 From: shihao zhong Date: Mon, 23 Nov 2026 22:20:36 -0500 Subject: [PATCH 1/4] Add pg_stat_tablespace view with temporary file statistics Entries exist for as long as the tablespace directory does. Temporary files are counted per tablespace. Catversion bump needed. --- doc/src/sgml/monitoring.sgml | 110 ++++++++ src/backend/catalog/system_views.sql | 10 + src/backend/commands/tablespace.c | 6 + src/backend/storage/file/fd.c | 34 ++- src/backend/storage/file/fileset.c | 5 +- src/backend/utils/activity/Makefile | 1 + src/backend/utils/activity/meson.build | 1 + src/backend/utils/activity/pgstat.c | 19 ++ .../utils/activity/pgstat_tablespace.c | 235 ++++++++++++++++++ src/backend/utils/adt/pgstatfuncs.c | 73 ++++++ src/include/catalog/pg_proc.dat | 11 + src/include/pgstat.h | 20 +- src/include/storage/fd.h | 5 +- src/include/utils/pgstat_internal.h | 15 ++ src/include/utils/pgstat_kind.h | 15 +- src/test/recovery/t/029_stats_restart.pl | 37 ++- .../recovery/t/030_stats_cleanup_replica.pl | 37 ++- src/test/regress/expected/rules.out | 7 + src/test/regress/expected/stats.out | 72 +++++- src/test/regress/expected/tablespace.out | 15 ++ src/test/regress/sql/stats.sql | 22 ++ src/test/regress/sql/tablespace.sql | 6 + src/tools/pgindent/typedefs.list | 3 + 23 files changed, 728 insertions(+), 31 deletions(-) create mode 100644 src/backend/utils/activity/pgstat_tablespace.c diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index 68803c58d1c..7fd0e65a4c9 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -563,6 +563,14 @@ postgres 27093 0.0 0.0 30096 2752 ? Ss 11:34 0:00 postgres: ser + + pg_stat_tablespacepg_stat_tablespace + One row per tablespace, showing tablespace-wide statistics. See + + pg_stat_tablespace for details. + + + pg_stat_walpg_stat_wal One row only, showing statistics about WAL activity. See @@ -4483,6 +4491,88 @@ description | Waiting for a newly initialized WAL file to reach durable storage + + <structname>pg_stat_tablespace</structname> + + + pg_stat_tablespace + + + + The pg_stat_tablespace view will contain + one row for each tablespace in the cluster, showing tablespace-wide + statistics. + + + + <structname>pg_stat_tablespace</structname> View + + + + + Column Type + + + Description + + + + + + + + spcid oid + + + OID of this tablespace + + + + + + spcname name + + + Name of this tablespace + + + + + + temp_files bigint + + + Number of temporary files created in this tablespace by queries in + any database, see . + All temporary files are counted, regardless of why the temporary file + was created (e.g., sorting or hashing), and regardless of the + setting. + + + + + + temp_bytes bigint + + + Total amount of data written to temporary files in this tablespace. + + + + + + stats_reset timestamp with time zone + + + Time at which these statistics were last reset + + + + +
+ +
+ <structname>pg_stat_all_tables</structname> @@ -6192,6 +6282,26 @@ description | Waiting for a newly initialized WAL file to reach durable storage can be granted EXECUTE to run the function.
+ + + + + pg_stat_reset_tablespace_stats + + pg_stat_reset_tablespace_stats ( oid ) + void + + + Resets statistics for a single tablespace shown in the + pg_stat_tablespace view to zero. If + the argument is NULL, reset statistics for all + tablespaces. + + + This function is restricted to superusers by default, but other users + can be granted EXECUTE to run the function. + + diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql index 6dce9192ba0..101dca04a1a 100644 --- a/src/backend/catalog/system_views.sql +++ b/src/backend/catalog/system_views.sql @@ -1146,6 +1146,16 @@ CREATE VIEW pg_stat_replication_slots AS LATERAL pg_stat_get_replication_slot(slot_name) as s WHERE r.datoid IS NOT NULL; -- excluding physical slots +CREATE VIEW pg_stat_tablespace AS + SELECT + t.oid AS spcid, + t.spcname, + s.temp_files, + s.temp_bytes, + s.stats_reset + FROM pg_tablespace AS t, + pg_stat_get_tablespace(t.oid) AS s; + CREATE VIEW pg_stat_database AS SELECT D.oid AS datid, diff --git a/src/backend/commands/tablespace.c b/src/backend/commands/tablespace.c index 7c40176b7b9..1545c3edc8d 100644 --- a/src/backend/commands/tablespace.c +++ b/src/backend/commands/tablespace.c @@ -68,6 +68,7 @@ #include "commands/tablespace.h" #include "common/file_perm.h" #include "miscadmin.h" +#include "pgstat.h" #include "postmaster/bgwriter.h" #include "storage/fd.h" #include "storage/lmgr.h" @@ -363,6 +364,8 @@ CreateTableSpace(CreateTableSpaceStmt *stmt) /* Post creation hook for new tablespace */ InvokeObjectPostCreateHook(TableSpaceRelationId, tablespaceoid, 0); + pgstat_create_tablespace(tablespaceoid); + create_tablespace_directories(location, tablespaceoid); /* Record the filesystem change in XLOG */ @@ -551,6 +554,8 @@ DropTableSpace(DropTableSpaceStmt *stmt) (void) XLogInsert(RM_TBLSPC_ID, XLOG_TBLSPC_DROP); } + pgstat_drop_tablespace(tablespaceoid); + /* * Note: because we checked that the tablespace was empty, there should be * no need to worry about flushing shared buffers or free space map @@ -1547,6 +1552,7 @@ tblspc_redo(XLogReaderState *record) char *location = xlrec->ts_path; create_tablespace_directories(location, xlrec->ts_id); + pgstat_create_tablespace_redo(xlrec->ts_id); } else if (info == XLOG_TBLSPC_DROP) { diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c index 443a5dd8f23..298153cbe42 100644 --- a/src/backend/storage/file/fd.c +++ b/src/backend/storage/file/fd.c @@ -205,6 +205,8 @@ typedef struct vfd File nextFree; /* link to next free VFD, if in freelist */ File lruMoreRecently; /* doubly linked recency-of-use list */ File lruLessRecently; + Oid tempTablespace; /* tablespace of file created by + * OpenTemporaryFile(), for stats */ pgoff_t fileSize; /* current size of file (0 if not temporary) */ char *fileName; /* name of file, or NULL for unused VFD */ /* NB: fileName is malloc'd, and must be free'd when closing the VFD */ @@ -283,6 +285,11 @@ static int numExternalFDs = 0; */ static long tempFileCounter = 0; +/* + * Tablespace of the directory PathNameDeleteTemporaryDir() is deleting. + */ +static Oid walkdirTablespace = InvalidOid; + /* * Array of OIDs of temp tablespaces. (Some entries may be InvalidOid, * indicating that the current database's default tablespace should be used.) @@ -1516,9 +1523,10 @@ FileAccess(File file) * Called whenever a temporary file is deleted to report its size. */ static void -ReportTemporaryFileUsage(const char *path, pgoff_t size) +ReportTemporaryFileUsage(const char *path, pgoff_t size, Oid tblspcOid) { pgstat_report_tempfile(size); + pgstat_report_tablespace_tempfile(tblspcOid, size); if (log_temp_files >= 0) { @@ -1676,10 +1684,11 @@ PathNameCreateTemporaryDir(const char *basedir, const char *directory) } /* - * Delete a directory and everything in it, if it exists. + * Delete a directory and everything in it, if it exists. tblspcOid is the + * tablespace the directory is in, to report the files deleted. */ void -PathNameDeleteTemporaryDir(const char *dirname) +PathNameDeleteTemporaryDir(const char *dirname, Oid tblspcOid) { struct stat statbuf; @@ -1692,8 +1701,10 @@ PathNameDeleteTemporaryDir(const char *dirname) * maintain state. Perhaps it should, so that we could tell the caller * whether this operation succeeded or failed. Since this operation is * used in a cleanup path, we wouldn't actually behave differently: we'll - * just log failures. + * just log failures. For the same reason, the tablespace is passed to + * unlink_if_exists_fname() in a static variable. */ + walkdirTablespace = tblspcOid; walkdir(dirname, unlink_if_exists_fname, false, LOG); } @@ -1832,6 +1843,9 @@ OpenTemporaryFileInTablespace(Oid tblspcOid, bool rejectError) tempfilepath); } + if (file > 0) + VfdCache[file].tempTablespace = tblspcOid; + return file; } @@ -1917,10 +1931,11 @@ PathNameOpenTemporaryFile(const char *path, int mode) /* * Delete a file by pathname. Return true if the file existed, false if - * didn't. + * didn't. tblspcOid is the tablespace the file is in, to report its size. */ bool -PathNameDeleteTemporaryFile(const char *path, bool error_on_failure) +PathNameDeleteTemporaryFile(const char *path, bool error_on_failure, + Oid tblspcOid) { struct stat filestats; int stat_errno; @@ -1950,7 +1965,7 @@ PathNameDeleteTemporaryFile(const char *path, bool error_on_failure) } if (stat_errno == 0) - ReportTemporaryFileUsage(path, filestats.st_size); + ReportTemporaryFileUsage(path, filestats.st_size, tblspcOid); else { errno = stat_errno; @@ -2038,7 +2053,8 @@ FileClose(File file) /* and last report the stat results */ if (stat_errno == 0) - ReportTemporaryFileUsage(vfdP->fileName, filestats.st_size); + ReportTemporaryFileUsage(vfdP->fileName, filestats.st_size, + vfdP->tempTablespace); else { errno = stat_errno; @@ -3832,7 +3848,7 @@ unlink_if_exists_fname(const char *fname, bool isdir, int elevel) else { /* Use PathNameDeleteTemporaryFile to report filesize */ - PathNameDeleteTemporaryFile(fname, false); + PathNameDeleteTemporaryFile(fname, false, walkdirTablespace); } } diff --git a/src/backend/storage/file/fileset.c b/src/backend/storage/file/fileset.c index e794cabcab8..669f9fbecc5 100644 --- a/src/backend/storage/file/fileset.c +++ b/src/backend/storage/file/fileset.c @@ -141,7 +141,8 @@ FileSetDelete(FileSet *fileset, const char *name, FilePath(path, fileset, name); - return PathNameDeleteTemporaryFile(path, error_on_failure); + return PathNameDeleteTemporaryFile(path, error_on_failure, + ChooseTablespace(fileset, name)); } /* @@ -161,7 +162,7 @@ FileSetDeleteAll(FileSet *fileset) for (i = 0; i < fileset->ntablespaces; ++i) { FileSetPath(dirpath, fileset, fileset->tablespaces[i]); - PathNameDeleteTemporaryDir(dirpath); + PathNameDeleteTemporaryDir(dirpath, fileset->tablespaces[i]); } } diff --git a/src/backend/utils/activity/Makefile b/src/backend/utils/activity/Makefile index 2e32d1485d6..e3292a22219 100644 --- a/src/backend/utils/activity/Makefile +++ b/src/backend/utils/activity/Makefile @@ -34,6 +34,7 @@ OBJS = \ pgstat_shmem.o \ pgstat_slru.o \ pgstat_subscription.o \ + pgstat_tablespace.o \ pgstat_wal.o \ pgstat_xact.o \ wait_event.o \ diff --git a/src/backend/utils/activity/meson.build b/src/backend/utils/activity/meson.build index e6dcb2e26fc..3049bdf4887 100644 --- a/src/backend/utils/activity/meson.build +++ b/src/backend/utils/activity/meson.build @@ -19,6 +19,7 @@ backend_sources += files( 'pgstat_shmem.c', 'pgstat_slru.c', 'pgstat_subscription.c', + 'pgstat_tablespace.c', 'pgstat_wal.c', 'pgstat_xact.c', ) diff --git a/src/backend/utils/activity/pgstat.c b/src/backend/utils/activity/pgstat.c index 5609e6ec072..0f150cd2363 100644 --- a/src/backend/utils/activity/pgstat.c +++ b/src/backend/utils/activity/pgstat.c @@ -397,6 +397,22 @@ static const PgStat_KindInfo pgstat_kind_builtin_infos[PGSTAT_KIND_BUILTIN_SIZE] .reset_timestamp_cb = pgstat_backend_reset_timestamp_cb, }, + [PGSTAT_KIND_TABLESPACE] = { + .name = "tablespace", + + .fixed_amount = false, + .write_to_file = true, + /* so pg_stat_tablespace entries can be seen in all databases */ + .accessed_across_databases = true, + + .shared_size = sizeof(PgStatShared_Tablespace), + .shared_data_off = offsetof(PgStatShared_Tablespace, stats), + .shared_data_len = sizeof(((PgStatShared_Tablespace *) 0)->stats), + + .flush_static_cb = pgstat_tablespace_flush_cb, + .reset_timestamp_cb = pgstat_tablespace_reset_timestamp_cb, + }, + /* stats for fixed-numbered (mostly 1) objects */ [PGSTAT_KIND_ARCHIVER] = { @@ -2261,6 +2277,9 @@ pgstat_reset_after_failure(void) /* and drop variable-numbered ones */ pgstat_drop_all_entries(); + + /* tablespaces keep an entry for as long as they exist */ + pgstat_create_all_tablespaces(); } /* diff --git a/src/backend/utils/activity/pgstat_tablespace.c b/src/backend/utils/activity/pgstat_tablespace.c new file mode 100644 index 00000000000..4ab3c90674d --- /dev/null +++ b/src/backend/utils/activity/pgstat_tablespace.c @@ -0,0 +1,235 @@ +/* ------------------------------------------------------------------------- + * + * pgstat_tablespace.c + * Implementation of tablespace statistics. + * + * This file contains the implementation of tablespace statistics. It is kept + * separate from other statistics implementations for the sake of readability. + * + * A tablespace has a stats entry for as long as it has a directory. Entries + * are created by CREATE TABLESPACE, by the replay of one, and for all the + * tablespaces found on disk when the stats are reset at startup. Nothing + * that counts creates an entry: by the time a count is reported its + * tablespace may have been dropped, and an entry created then would never be + * removed. Counts for a tablespace without an entry are discarded. + * + * Counts are kept in process-local memory until they are flushed. Pending + * entries would not do for that, as those create the entry they are for. + * + * Copyright (c) 2026, PostgreSQL Global Development Group + * + * IDENTIFICATION + * src/backend/utils/activity/pgstat_tablespace.c + * ------------------------------------------------------------------------- + */ + +#include "postgres.h" + +#include "catalog/pg_tablespace_d.h" +#include "common/relpath.h" +#include "storage/fd.h" +#include "utils/memutils.h" +#include "utils/pgstat_internal.h" + + +/* + * Counts of a tablespace that are not flushed yet. These are never freed. + */ +typedef struct PgStat_PendingTablespace +{ + Oid spcoid; + PgStat_Counter temp_files; + PgStat_Counter temp_bytes; + struct PgStat_PendingTablespace *next; +} PgStat_PendingTablespace; + +static PgStat_PendingTablespace *pending_tablespaces = NULL; + + +/* + * Report creating the tablespace. + */ +void +pgstat_create_tablespace(Oid spcoid) +{ + /* Ensures that stats are dropped if transaction rolls back */ + pgstat_create_transactional(PGSTAT_KIND_TABLESPACE, InvalidOid, spcoid); + + pgstat_get_entry_ref(PGSTAT_KIND_TABLESPACE, InvalidOid, spcoid, + true, NULL); +} + +/* + * Report the replay of the creation of a tablespace. + * + * The entry is removed again by the commit record of DROP TABLESPACE, or by + * the abort record of the transaction creating the tablespace. + */ +void +pgstat_create_tablespace_redo(Oid spcoid) +{ + pgstat_get_entry_ref(PGSTAT_KIND_TABLESPACE, InvalidOid, spcoid, + true, NULL); +} + +/* + * Report dropping the tablespace. + * + * Ensures that stats are dropped if transaction commits. + */ +void +pgstat_drop_tablespace(Oid spcoid) +{ + pgstat_drop_transactional(PGSTAT_KIND_TABLESPACE, InvalidOid, spcoid); +} + +/* + * Create the entries of all the tablespaces that exist on disk. + * + * This runs after the stats were reset at startup, and thus also when a + * cluster or a base backup is started for the first time. + */ +void +pgstat_create_all_tablespaces(void) +{ + DIR *dir; + struct dirent *de; + + /* these two have no link in pg_tblspc */ + pgstat_get_entry_ref(PGSTAT_KIND_TABLESPACE, InvalidOid, + DEFAULTTABLESPACE_OID, true, NULL); + pgstat_get_entry_ref(PGSTAT_KIND_TABLESPACE, InvalidOid, + GLOBALTABLESPACE_OID, true, NULL); + + dir = AllocateDir(PG_TBLSPC_DIR); + while ((de = ReadDirExtended(dir, PG_TBLSPC_DIR, LOG)) != NULL) + { + /* links are named after the OID of their tablespace */ + if (strspn(de->d_name, "0123456789") != strlen(de->d_name)) + continue; + + pgstat_get_entry_ref(PGSTAT_KIND_TABLESPACE, InvalidOid, + atooid(de->d_name), true, NULL); + } + FreeDir(dir); +} + +/* + * Return the pending counts of a tablespace, or NULL if there is no memory + * for them. + */ +static PgStat_PendingTablespace * +pgstat_tablespace_pending(Oid spcoid) +{ + PgStat_PendingTablespace *pending; + + for (pending = pending_tablespaces; pending != NULL; pending = pending->next) + { + if (pending->spcoid == spcoid) + return pending; + } + + pending = MemoryContextAllocExtended(TopMemoryContext, + sizeof(PgStat_PendingTablespace), + MCXT_ALLOC_NO_OOM | MCXT_ALLOC_ZERO); + if (pending == NULL) + return NULL; + + pending->spcoid = spcoid; + pending->next = pending_tablespaces; + pending_tablespaces = pending; + + return pending; +} + +/* + * Report a temporary file removed from a tablespace. + * + * This runs when files are cleaned up, also after an error, so it does + * without the count rather than fail if there is no memory to keep it. + */ +void +pgstat_report_tablespace_tempfile(Oid spcoid, size_t filesize) +{ + PgStat_PendingTablespace *pending; + + if (!pgstat_track_counts) + return; + + /* like TempTablespacePath(), which uses pg_default for these */ + if (spcoid == InvalidOid || spcoid == GLOBALTABLESPACE_OID) + spcoid = DEFAULTTABLESPACE_OID; + + pending = pgstat_tablespace_pending(spcoid); + if (pending == NULL) + return; + + pending->temp_files++; + pending->temp_bytes += filesize; + + pgstat_report_fixed = true; +} + +/* + * Flush out locally pending tablespace statistics. + * + * If nowait is true, this function returns true if the lock of some entry + * could not be acquired, whose counts are then kept for the next call. + * Otherwise, return false. + */ +bool +pgstat_tablespace_flush_cb(bool nowait) +{ + bool partial = false; + + for (PgStat_PendingTablespace *pending = pending_tablespaces; + pending != NULL; pending = pending->next) + { + PgStat_EntryRef *entry_ref; + PgStatShared_Tablespace *shtsent; + + if (pending->temp_files == 0) + continue; + + entry_ref = pgstat_get_entry_ref(PGSTAT_KIND_TABLESPACE, InvalidOid, + pending->spcoid, false, NULL); + + if (entry_ref != NULL) + { + if (!pgstat_lock_entry(entry_ref, nowait)) + { + partial = true; + continue; + } + + shtsent = (PgStatShared_Tablespace *) entry_ref->shared_stats; + shtsent->stats.temp_files += pending->temp_files; + shtsent->stats.temp_bytes += pending->temp_bytes; + + pgstat_unlock_entry(entry_ref); + } + + /* the counts are discarded if the tablespace has been dropped */ + pending->temp_files = 0; + pending->temp_bytes = 0; + } + + return partial; +} + +/* + * Support function for the SQL-callable pgstat* functions. Returns the + * collected statistics for one tablespace or NULL. + */ +PgStat_StatTablespaceEntry * +pgstat_fetch_stat_tablespace(Oid spcoid) +{ + return (PgStat_StatTablespaceEntry *) + pgstat_fetch_entry(PGSTAT_KIND_TABLESPACE, InvalidOid, spcoid, NULL); +} + +void +pgstat_tablespace_reset_timestamp_cb(PgStatShared_Common *header, TimestampTz ts) +{ + ((PgStatShared_Tablespace *) header)->stats.stat_reset_timestamp = ts; +} diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c index 64b6f60516c..be960aed02b 100644 --- a/src/backend/utils/adt/pgstatfuncs.c +++ b/src/backend/utils/adt/pgstatfuncs.c @@ -2260,6 +2260,31 @@ pg_stat_reset_subscription_stats(PG_FUNCTION_ARGS) PG_RETURN_VOID(); } +/* Reset tablespace stats (a specific one or all of them) */ +Datum +pg_stat_reset_tablespace_stats(PG_FUNCTION_ARGS) +{ + Oid spcoid; + + if (PG_ARGISNULL(0)) + { + /* Clear all tablespace stats */ + pgstat_reset_of_kind(PGSTAT_KIND_TABLESPACE); + } + else + { + spcoid = PG_GETARG_OID(0); + + if (!OidIsValid(spcoid)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("invalid tablespace OID %u", spcoid))); + pgstat_reset(PGSTAT_KIND_TABLESPACE, InvalidOid, spcoid); + } + + PG_RETURN_VOID(); +} + Datum pg_stat_get_archiver(PG_FUNCTION_ARGS) { @@ -2493,6 +2518,54 @@ pg_stat_get_subscription_stats(PG_FUNCTION_ARGS) PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls))); } +/* + * Get the statistics for the given tablespace. If the tablespace statistics + * are not available, return all-zero stats. + */ +Datum +pg_stat_get_tablespace(PG_FUNCTION_ARGS) +{ +#define PG_STAT_GET_TABLESPACE_COLS 3 + Oid spcoid = PG_GETARG_OID(0); + TupleDesc tupdesc; + Datum values[PG_STAT_GET_TABLESPACE_COLS] = {0}; + bool nulls[PG_STAT_GET_TABLESPACE_COLS] = {0}; + PgStat_StatTablespaceEntry *tsentry; + PgStat_StatTablespaceEntry allzero; + int i = 0; + + tupdesc = CreateTemplateTupleDesc(PG_STAT_GET_TABLESPACE_COLS); + TupleDescInitEntry(tupdesc, (AttrNumber) 1, "temp_files", + INT8OID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 2, "temp_bytes", + INT8OID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 3, "stats_reset", + TIMESTAMPTZOID, -1, 0); + TupleDescFinalize(tupdesc); + BlessTupleDesc(tupdesc); + + /* Get tablespace stats */ + tsentry = pgstat_fetch_stat_tablespace(spcoid); + if (!tsentry) + { + memset(&allzero, 0, sizeof(PgStat_StatTablespaceEntry)); + tsentry = &allzero; + } + + values[i++] = Int64GetDatum(tsentry->temp_files); + values[i++] = Int64GetDatum(tsentry->temp_bytes); + + if (tsentry->stat_reset_timestamp == 0) + nulls[i] = true; + else + values[i] = TimestampTzGetDatum(tsentry->stat_reset_timestamp); + + Assert(i + 1 == PG_STAT_GET_TABLESPACE_COLS); + + PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls))); +#undef PG_STAT_GET_TABLESPACE_COLS +} + /* * Checks for presence of stats for object with provided kind, database oid, * object oid. diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 50fb182cb79..8f8f8fb87d2 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -5746,6 +5746,12 @@ proargmodes => '{i,o,o,o,o,o,o,o,o,o,o,o,o,o}', proargnames => '{subid,subid,apply_error_count,sync_seq_error_count,sync_table_error_count,confl_insert_exists,confl_update_origin_differs,confl_update_exists,confl_update_deleted,confl_update_missing,confl_delete_origin_differs,confl_delete_missing,confl_multiple_unique_conflicts,stats_reset}', prosrc => 'pg_stat_get_subscription_stats' }, +{ oid => '8463', descr => 'statistics: information about tablespace stats', + proname => 'pg_stat_get_tablespace', provolatile => 's', proparallel => 'r', + prorettype => 'record', proargtypes => 'oid', + proallargtypes => '{oid,int8,int8,timestamptz}', proargmodes => '{i,o,o,o}', + proargnames => '{spcid,temp_files,temp_bytes,stats_reset}', + prosrc => 'pg_stat_get_tablespace' }, { oid => '6118', descr => 'statistics: information about subscription', proname => 'pg_stat_get_subscription', prorows => '10', proisstrict => 'f', proretset => 't', provolatile => 's', proparallel => 'r', @@ -6323,6 +6329,11 @@ proname => 'pg_stat_reset_subscription_stats', proisstrict => 'f', provolatile => 'v', prorettype => 'void', proargtypes => 'oid', prosrc => 'pg_stat_reset_subscription_stats', proacl => '{POSTGRES=X}' }, +{ oid => '8464', + descr => 'statistics: reset collected statistics for a single tablespace', + proname => 'pg_stat_reset_tablespace_stats', proisstrict => 'f', + provolatile => 'v', prorettype => 'void', proargtypes => 'oid', + prosrc => 'pg_stat_reset_tablespace_stats', proacl => '{POSTGRES=X}' }, { oid => '3163', descr => 'current trigger depth', proname => 'pg_trigger_depth', provolatile => 's', proparallel => 'r', diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 9b99062f853..f29b3ddba7a 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -275,7 +275,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCBD +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCBE typedef struct PgStat_ArchiverStats { @@ -544,6 +544,13 @@ typedef struct PgStat_StatTabEntry TimestampTz stat_reset_time; } PgStat_StatTabEntry; +typedef struct PgStat_StatTablespaceEntry +{ + PgStat_Counter temp_files; + PgStat_Counter temp_bytes; + TimestampTz stat_reset_timestamp; +} PgStat_StatTablespaceEntry; + typedef struct PgStat_StatIdxEntry { PgStat_Counter numscans; @@ -927,6 +934,17 @@ extern void pgstat_drop_subscription(Oid subid); extern PgStat_StatSubEntry *pgstat_fetch_stat_subscription(Oid subid); +/* + * Functions in pgstat_tablespace.c + */ + +extern void pgstat_create_tablespace(Oid spcoid); +extern void pgstat_create_tablespace_redo(Oid spcoid); +extern void pgstat_drop_tablespace(Oid spcoid); +extern void pgstat_report_tablespace_tempfile(Oid spcoid, size_t filesize); +extern PgStat_StatTablespaceEntry *pgstat_fetch_stat_tablespace(Oid spcoid); + + /* * Functions in pgstat_xact.c */ diff --git a/src/include/storage/fd.h b/src/include/storage/fd.h index 8ac466fd346..acb4c965ed8 100644 --- a/src/include/storage/fd.h +++ b/src/include/storage/fd.h @@ -153,9 +153,10 @@ extern mode_t FileGetRawMode(File file); /* Operations used for sharing named temporary files */ extern File PathNameCreateTemporaryFile(const char *path, bool error_on_failure); extern File PathNameOpenTemporaryFile(const char *path, int mode); -extern bool PathNameDeleteTemporaryFile(const char *path, bool error_on_failure); +extern bool PathNameDeleteTemporaryFile(const char *path, bool error_on_failure, + Oid tblspcOid); extern void PathNameCreateTemporaryDir(const char *basedir, const char *directory); -extern void PathNameDeleteTemporaryDir(const char *dirname); +extern void PathNameDeleteTemporaryDir(const char *dirname, Oid tblspcOid); extern void TempTablespacePath(char *path, Oid tablespace); /* Operations that allow use of regular stdio --- USE WITH CAUTION */ diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h index 33fc58feb99..208ea083200 100644 --- a/src/include/utils/pgstat_internal.h +++ b/src/include/utils/pgstat_internal.h @@ -536,6 +536,12 @@ typedef struct PgStatShared_Subscription PgStat_StatSubEntry stats; } PgStatShared_Subscription; +typedef struct PgStatShared_Tablespace +{ + PgStatShared_Common header; + PgStat_StatTablespaceEntry stats; +} PgStatShared_Tablespace; + typedef struct PgStatShared_ReplSlot { PgStatShared_Common header; @@ -890,6 +896,15 @@ extern bool pgstat_subscription_flush_cb(PgStat_EntryRef *entry_ref, bool nowait extern void pgstat_subscription_reset_timestamp_cb(PgStatShared_Common *header, TimestampTz ts); +/* + * Functions in pgstat_tablespace.c + */ + +extern void pgstat_create_all_tablespaces(void); +extern bool pgstat_tablespace_flush_cb(bool nowait); +extern void pgstat_tablespace_reset_timestamp_cb(PgStatShared_Common *header, TimestampTz ts); + + /* * Functions in pgstat_xact.c */ diff --git a/src/include/utils/pgstat_kind.h b/src/include/utils/pgstat_kind.h index 45ca599d0dd..811b79f3b10 100644 --- a/src/include/utils/pgstat_kind.h +++ b/src/include/utils/pgstat_kind.h @@ -31,15 +31,16 @@ #define PGSTAT_KIND_REPLSLOT 5 /* per-slot statistics */ #define PGSTAT_KIND_SUBSCRIPTION 6 /* per-subscription statistics */ #define PGSTAT_KIND_BACKEND 7 /* per-backend statistics */ +#define PGSTAT_KIND_TABLESPACE 8 /* per-tablespace statistics */ /* stats for fixed-numbered objects */ -#define PGSTAT_KIND_ARCHIVER 8 -#define PGSTAT_KIND_BGWRITER 9 -#define PGSTAT_KIND_CHECKPOINTER 10 -#define PGSTAT_KIND_IO 11 -#define PGSTAT_KIND_LOCK 12 -#define PGSTAT_KIND_SLRU 13 -#define PGSTAT_KIND_WAL 14 +#define PGSTAT_KIND_ARCHIVER 9 +#define PGSTAT_KIND_BGWRITER 10 +#define PGSTAT_KIND_CHECKPOINTER 11 +#define PGSTAT_KIND_IO 12 +#define PGSTAT_KIND_LOCK 13 +#define PGSTAT_KIND_SLRU 14 +#define PGSTAT_KIND_WAL 15 #define PGSTAT_KIND_BUILTIN_MIN PGSTAT_KIND_DATABASE #define PGSTAT_KIND_BUILTIN_MAX PGSTAT_KIND_WAL diff --git a/src/test/recovery/t/029_stats_restart.pl b/src/test/recovery/t/029_stats_restart.pl index cdc427dbc78..42f23e1edd8 100644 --- a/src/test/recovery/t/029_stats_restart.pl +++ b/src/test/recovery/t/029_stats_restart.pl @@ -12,7 +12,8 @@ use File::Copy; my $node = PostgreSQL::Test::Cluster->new('primary'); $node->init(allows_streaming => 1); -$node->append_conf('postgresql.conf', "track_functions = 'all'"); +$node->append_conf('postgresql.conf', + "track_functions = 'all'\nallow_in_place_tablespaces = on"); $node->start; my $connect_db = 'postgres'; @@ -42,7 +43,12 @@ $node->safe_psql($db_under_test, "CREATE FUNCTION func_stats_crash_discard1() RETURNS VOID AS 'select 2;' LANGUAGE SQL IMMUTABLE" ); +$node->safe_psql($connect_db, + "CREATE TABLESPACE test_stats_tblspc LOCATION ''"); + # collect object oids +my $spcoid = $node->safe_psql($connect_db, + "SELECT oid FROM pg_tablespace WHERE spcname = 'test_stats_tblspc'"); my $dboid = $node->safe_psql($db_under_test, "SELECT oid FROM pg_database WHERE datname = '$db_under_test'"); my $funcoid = $node->safe_psql($db_under_test, @@ -52,6 +58,7 @@ my $tableoid = $node->safe_psql($db_under_test, # generate stats and flush them trigger_funcrel_stat(); +trigger_tablespace_stat(); # verify stats objects exist $sect = "initial"; @@ -84,6 +91,8 @@ is(have_stats('function', $dboid, $funcoid), 't', "$sect: function stats do exist"); is(have_stats('relation', $dboid, $tableoid), 't', "$sect: relation stats do exist"); +is(tablespace_temp_files_counted(), + 't', "$sect: tablespace stats were restored"); $node->stop('immediate'); @@ -102,14 +111,23 @@ is(have_stats('function', $dboid, $funcoid), is(have_stats('relation', $dboid, $tableoid), 'f', "$sect: relation stats do not exist"); +# tablespaces get their stats back, with the counts gone +is(have_stats('tablespace', 0, $spcoid), + 't', "$sect: tablespace stats do exist"); +is(tablespace_temp_files_counted(), + 'f', "$sect: tablespace stats were reset"); + # get rid of backup statsfile unlink $statsfile or die "cannot unlink $statsfile $!"; # generate new stats and flush them trigger_funcrel_stat(); +trigger_tablespace_stat(); $sect = "post immediate, new"; +is(tablespace_temp_files_counted(), + 't', "$sect: tablespace stats are counted"); is(have_stats('database', $dboid, 0), 't', "$sect: db stats do exist"); is(have_stats('function', $dboid, $funcoid), 't', "$sect: function stats do exist"); @@ -305,6 +323,23 @@ sub trigger_funcrel_stat SELECT pg_stat_force_next_flush();]); } +sub trigger_tablespace_stat +{ + $node->safe_psql( + $connect_db, q[ + SET temp_tablespaces = test_stats_tblspc; + SET work_mem = '64kB'; + SELECT count(*) FROM (SELECT * FROM generate_series(1, 10000) g ORDER BY g) s; + SELECT pg_stat_force_next_flush();] + ); +} + +sub tablespace_temp_files_counted +{ + return $node->safe_psql($connect_db, + "SELECT temp_files > 0 FROM pg_stat_tablespace WHERE spcid = $spcoid"); +} + sub have_stats { my ($kind, $dboid, $objid) = @_; diff --git a/src/test/recovery/t/030_stats_cleanup_replica.pl b/src/test/recovery/t/030_stats_cleanup_replica.pl index a7cbe99930a..a4e7b7fda36 100644 --- a/src/test/recovery/t/030_stats_cleanup_replica.pl +++ b/src/test/recovery/t/030_stats_cleanup_replica.pl @@ -13,7 +13,8 @@ use Test::More; my $node_primary = PostgreSQL::Test::Cluster->new('primary'); $node_primary->init(allows_streaming => 1); -$node_primary->append_conf('postgresql.conf', "track_functions = 'all'"); +$node_primary->append_conf('postgresql.conf', + "track_functions = 'all'\nallow_in_place_tablespaces = on"); $node_primary->start; my $backup_name = 'my_backup'; @@ -92,6 +93,28 @@ test_standby_func_tab_stats_status('postgres', test_standby_db_stats_status('postgres', $dboid, 'f'); +## Test that tablespace stats follow the replay of CREATE TABLESPACE and +## DROP TABLESPACE + +$node_primary->safe_psql('postgres', + "CREATE TABLESPACE test_stats_tblspc1 LOCATION ''"); +$node_primary->safe_psql('postgres', + "CREATE TABLESPACE test_stats_tblspc2 LOCATION ''"); +my ($spcoid1, $spcoid2) = split(/\n/, + $node_primary->safe_psql( + 'postgres', + "SELECT oid FROM pg_tablespace WHERE spcname LIKE 'test_stats_tblspc_' ORDER BY spcname" + )); +$node_primary->wait_for_replay_catchup($node_standby); +is(standby_have_tablespace_stats($spcoid1), + 't', "tablespace stats exist after replay of its creation"); + +$node_primary->safe_psql('postgres', "DROP TABLESPACE test_stats_tblspc1"); +$node_primary->wait_for_replay_catchup($node_standby); +is(standby_have_tablespace_stats($spcoid1), + 'f', "tablespace stats do not exist after replay of its drop"); + + ## verify that stats persist across graceful restarts on a replica # NB: Can't test database stats, they're immediately repopulated when @@ -117,6 +140,10 @@ $sect = "post immediate restart"; test_standby_func_tab_stats_status('postgres', $dboid, $tableoid, $funcoid, 'f'); +# unlike the stats of the tablespaces found on disk +is(standby_have_tablespace_stats($spcoid2), + 't', "$sect: tablespace stats do exist"); + done_testing(); @@ -198,3 +225,11 @@ sub test_standby_db_stats_status $present, "$sect: standby db stats as expected"); } + +sub standby_have_tablespace_stats +{ + my ($spcoid) = @_; + + return $node_standby->safe_psql('postgres', + "SELECT pg_stat_have_stats('tablespace', 0, $spcoid)"); +} diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index cf00b58fcbb..d649934669c 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -2378,6 +2378,13 @@ pg_stat_sys_tables| SELECT relid, stats_reset FROM pg_stat_all_tables WHERE ((schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (schemaname ~ '^pg_toast'::text)); +pg_stat_tablespace| SELECT t.oid AS spcid, + t.spcname, + s.temp_files, + s.temp_bytes, + s.stats_reset + FROM pg_tablespace t, + LATERAL pg_stat_get_tablespace(t.oid) s(temp_files, temp_bytes, stats_reset); pg_stat_user_functions| SELECT p.oid AS funcid, n.nspname AS schemaname, p.proname AS funcname, diff --git a/src/test/regress/expected/stats.out b/src/test/regress/expected/stats.out index 0e54cf0d394..0de28403139 100644 --- a/src/test/regress/expected/stats.out +++ b/src/test/regress/expected/stats.out @@ -122,14 +122,15 @@ SELECT id, name, fixed_amount, 5 | replslot | f | t | t 6 | subscription | f | t | t 7 | backend | f | t | f - 8 | archiver | t | f | t - 9 | bgwriter | t | f | t - 10 | checkpointer | t | f | t - 11 | io | t | f | t - 12 | lock | t | f | t - 13 | slru | t | f | t - 14 | wal | t | f | t -(14 rows) + 8 | tablespace | f | t | t + 9 | archiver | t | f | t + 10 | bgwriter | t | f | t + 11 | checkpointer | t | f | t + 12 | io | t | f | t + 13 | lock | t | f | t + 14 | slru | t | f | t + 15 | wal | t | f | t +(15 rows) -- ensure that both seqscan and indexscan plans are allowed SET enable_seqscan TO on; @@ -2184,4 +2185,59 @@ SELECT fastpath_exceeded > :backend_fastpath_exceeded_before (1 row) DROP TABLE part_test; +-- Test pg_stat_tablespace +SELECT oid AS spcoid FROM pg_tablespace + WHERE spcname = 'regress_tblspace' \gset +SELECT temp_files AS spc_temp_files_before + FROM pg_stat_tablespace WHERE spcid = :spcoid \gset +BEGIN; +SET LOCAL temp_tablespaces = regress_tblspace; +SET LOCAL work_mem = '64kB'; +SELECT count(*) FROM (SELECT g FROM generate_series(1, 10000) g ORDER BY g) s; + count +------- + 10000 +(1 row) + +COMMIT; +SELECT pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT temp_files > :spc_temp_files_before AS files, temp_bytes > 0 AS bytes + FROM pg_stat_tablespace WHERE spcid = :spcoid; + files | bytes +-------+------- + t | t +(1 row) + +SELECT pg_stat_reset_tablespace_stats(:spcoid); + pg_stat_reset_tablespace_stats +-------------------------------- + +(1 row) + +SELECT temp_files, temp_bytes, stats_reset AS spc_stats_reset + FROM pg_stat_tablespace WHERE spcid = :spcoid \gset +SELECT :temp_files, :temp_bytes; + ?column? | ?column? +----------+---------- + 0 | 0 +(1 row) + +SELECT pg_stat_reset_tablespace_stats(NULL); + pg_stat_reset_tablespace_stats +-------------------------------- + +(1 row) + +SELECT stats_reset > :'spc_stats_reset'::timestamptz + FROM pg_stat_tablespace WHERE spcid = :spcoid; + ?column? +---------- + t +(1 row) + -- End of Stats Test diff --git a/src/test/regress/expected/tablespace.out b/src/test/regress/expected/tablespace.out index f0dd25cdf0c..8541bbbd22a 100644 --- a/src/test/regress/expected/tablespace.out +++ b/src/test/regress/expected/tablespace.out @@ -20,8 +20,23 @@ SELECT spcoptions FROM pg_tablespace WHERE spcname = 'regress_tblspacewith'; {random_page_cost=3.0} (1 row) +-- its stats entry exists, and goes away with it +SELECT oid AS spcoid FROM pg_tablespace + WHERE spcname = 'regress_tblspacewith' \gset +SELECT pg_stat_have_stats('tablespace', 0, :spcoid); + pg_stat_have_stats +-------------------- + t +(1 row) + -- drop the tablespace so we can re-use the location DROP TABLESPACE regress_tblspacewith; +SELECT pg_stat_have_stats('tablespace', 0, :spcoid); + pg_stat_have_stats +-------------------- + f +(1 row) + -- This returns a relative path as of an effect of allow_in_place_tablespaces, -- masking the tablespace OID used in the path name. SELECT regexp_replace(pg_tablespace_location(oid), '(pg_tblspc)/(\d+)', '\1/NNN') diff --git a/src/test/regress/sql/stats.sql b/src/test/regress/sql/stats.sql index f4931fd84de..c7b616ebc77 100644 --- a/src/test/regress/sql/stats.sql +++ b/src/test/regress/sql/stats.sql @@ -1080,4 +1080,26 @@ SELECT fastpath_exceeded > :backend_fastpath_exceeded_before DROP TABLE part_test; +-- Test pg_stat_tablespace +SELECT oid AS spcoid FROM pg_tablespace + WHERE spcname = 'regress_tblspace' \gset +SELECT temp_files AS spc_temp_files_before + FROM pg_stat_tablespace WHERE spcid = :spcoid \gset +BEGIN; +SET LOCAL temp_tablespaces = regress_tblspace; +SET LOCAL work_mem = '64kB'; +SELECT count(*) FROM (SELECT g FROM generate_series(1, 10000) g ORDER BY g) s; +COMMIT; +SELECT pg_stat_force_next_flush(); +SELECT temp_files > :spc_temp_files_before AS files, temp_bytes > 0 AS bytes + FROM pg_stat_tablespace WHERE spcid = :spcoid; + +SELECT pg_stat_reset_tablespace_stats(:spcoid); +SELECT temp_files, temp_bytes, stats_reset AS spc_stats_reset + FROM pg_stat_tablespace WHERE spcid = :spcoid \gset +SELECT :temp_files, :temp_bytes; +SELECT pg_stat_reset_tablespace_stats(NULL); +SELECT stats_reset > :'spc_stats_reset'::timestamptz + FROM pg_stat_tablespace WHERE spcid = :spcoid; + -- End of Stats Test diff --git a/src/test/regress/sql/tablespace.sql b/src/test/regress/sql/tablespace.sql index c43a59e5957..437c73549fb 100644 --- a/src/test/regress/sql/tablespace.sql +++ b/src/test/regress/sql/tablespace.sql @@ -17,8 +17,14 @@ CREATE TABLESPACE regress_tblspacewith LOCATION '' WITH (random_page_cost = 3.0) -- check to see the parameter was used SELECT spcoptions FROM pg_tablespace WHERE spcname = 'regress_tblspacewith'; +-- its stats entry exists, and goes away with it +SELECT oid AS spcoid FROM pg_tablespace + WHERE spcname = 'regress_tblspacewith' \gset +SELECT pg_stat_have_stats('tablespace', 0, :spcoid); + -- drop the tablespace so we can re-use the location DROP TABLESPACE regress_tblspacewith; +SELECT pg_stat_have_stats('tablespace', 0, :spcoid); -- This returns a relative path as of an effect of allow_in_place_tablespaces, -- masking the tablespace OID used in the path name. diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index f10eb469266..926dc1213af 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2312,6 +2312,7 @@ PgStatShared_Relation PgStatShared_ReplSlot PgStatShared_SLRU PgStatShared_Subscription +PgStatShared_Tablespace PgStatShared_Wal PgStat_ArchiverStats PgStat_Backend @@ -2336,6 +2337,7 @@ PgStat_LockEntry PgStat_PendingDroppedStatsItem PgStat_PendingIO PgStat_PendingLock +PgStat_PendingTablespace PgStat_RelationStatus PgStat_SLRUStats PgStat_ShmemControl @@ -2349,6 +2351,7 @@ PgStat_StatIdxEntry PgStat_StatReplSlotEntry PgStat_StatSubEntry PgStat_StatTabEntry +PgStat_StatTablespaceEntry PgStat_StatsFileOp PgStat_SubXactStatus PgStat_TableCounts -- 2.37.1 (Apple Git-137.1)