| 1 |
/*------------------------------------------------------------------------- |
| 2 |
* |
| 3 |
* autovacuum.c |
| 4 |
* |
| 5 |
* PostgreSQL Integrated Autovacuum Daemon |
| 6 |
* |
| 7 |
* The autovacuum system is structured in two different kinds of processes: the |
| 8 |
* autovacuum launcher and the autovacuum worker. The launcher is an |
| 9 |
* always-running process, started by the postmaster when the autovacuum GUC |
| 10 |
* parameter is set. The launcher schedules autovacuum workers to be started |
| 11 |
* when appropriate. The workers are the processes which execute the actual |
| 12 |
* vacuuming; they connect to a database as determined in the launcher, and |
| 13 |
* once connected they examine the catalogs to select the tables to vacuum. |
| 14 |
* |
| 15 |
* The autovacuum launcher cannot start the worker processes by itself, |
| 16 |
* because doing so would cause robustness issues (namely, failure to shut |
| 17 |
* them down on exceptional conditions, and also, since the launcher is |
| 18 |
* connected to shared memory and is thus subject to corruption there, it is |
| 19 |
* not as robust as the postmaster). So it leaves that task to the postmaster. |
| 20 |
* |
| 21 |
* There is an autovacuum shared memory area, where the launcher stores |
| 22 |
* information about the database it wants vacuumed. When it wants a new |
| 23 |
* worker to start, it sets a flag in shared memory and sends a signal to the |
| 24 |
* postmaster. Then postmaster knows nothing more than it must start a worker; |
| 25 |
* so it forks a new child, which turns into a worker. This new process |
| 26 |
* connects to shared memory, and there it can inspect the information that the |
| 27 |
* launcher has set up. |
| 28 |
* |
| 29 |
* If the fork() call fails in the postmaster, it sets a flag in the shared |
| 30 |
* memory area, and sends a signal to the launcher. The launcher, upon |
| 31 |
* noticing the flag, can try starting the worker again by resending the |
| 32 |
* signal. Note that the failure can only be transient (fork failure due to |
| 33 |
* high load, memory pressure, too many processes, etc); more permanent |
| 34 |
* problems, like failure to connect to a database, are detected later in the |
| 35 |
* worker and dealt with just by having the worker exit normally. The launcher |
| 36 |
* will launch a new worker again later, per schedule. |
| 37 |
* |
| 38 |
* When the worker is done vacuuming it sends SIGUSR2 to the launcher. The |
| 39 |
* launcher then wakes up and is able to launch another worker, if the schedule |
| 40 |
* is so tight that a new worker is needed immediately. At this time the |
| 41 |
* launcher can also balance the settings for the various remaining workers' |
| 42 |
* cost-based vacuum delay feature. |
| 43 |
* |
| 44 |
* Note that there can be more than one worker in a database concurrently. |
| 45 |
* They will store the table they are currently vacuuming in shared memory, so |
| 46 |
* that other workers avoid being blocked waiting for the vacuum lock for that |
| 47 |
* table. They will also fetch the last time the table was vacuumed from |
| 48 |
* pgstats just before vacuuming each table, to avoid vacuuming a table that |
| 49 |
* was just finished being vacuumed by another worker and thus is no longer |
| 50 |
* noted in shared memory. However, there is a small window (due to not yet |
| 51 |
* holding the relation lock) during which a worker may choose a table that was |
| 52 |
* already vacuumed; this is a bug in the current design. |
| 53 |
* |
| 54 |
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
| 55 |
* Portions Copyright (c) 1994, Regents of the University of California |
| 56 |
* |
| 57 |
* |
| 58 |
* IDENTIFICATION |
| 59 |
* src/backend/postmaster/autovacuum.c |
| 60 |
* |
| 61 |
*------------------------------------------------------------------------- |
| 62 |
*/ |
| 63 |
#include "postgres.h" |
| 64 |
|
| 65 |
#include <signal.h> |
| 66 |
#include <sys/time.h> |
| 67 |
#include <unistd.h> |
| 68 |
|
| 69 |
#include "access/heapam.h" |
| 70 |
#include "access/htup_details.h" |
| 71 |
#include "access/multixact.h" |
| 72 |
#include "access/reloptions.h" |
| 73 |
#include "access/tableam.h" |
| 74 |
#include "access/transam.h" |
| 75 |
#include "access/xact.h" |
| 76 |
#include "catalog/dependency.h" |
| 77 |
#include "catalog/namespace.h" |
| 78 |
#include "catalog/pg_database.h" |
| 79 |
#include "catalog/pg_namespace.h" |
| 80 |
#include "commands/dbcommands.h" |
| 81 |
#include "commands/vacuum.h" |
| 82 |
#include "common/int.h" |
| 83 |
#include "lib/ilist.h" |
| 84 |
#include "libpq/pqsignal.h" |
| 85 |
#include "miscadmin.h" |
| 86 |
#include "nodes/makefuncs.h" |
| 87 |
#include "pgstat.h" |
| 88 |
#include "postmaster/autovacuum.h" |
| 89 |
#include "postmaster/interrupt.h" |
| 90 |
#include "postmaster/postmaster.h" |
| 91 |
#include "storage/aio_subsys.h" |
| 92 |
#include "storage/bufmgr.h" |
| 93 |
#include "storage/ipc.h" |
| 94 |
#include "storage/latch.h" |
| 95 |
#include "storage/lmgr.h" |
| 96 |
#include "storage/pmsignal.h" |
| 97 |
#include "storage/proc.h" |
| 98 |
#include "storage/procsignal.h" |
| 99 |
#include "storage/smgr.h" |
| 100 |
#include "tcop/tcopprot.h" |
| 101 |
#include "utils/fmgroids.h" |
| 102 |
#include "utils/fmgrprotos.h" |
| 103 |
#include "utils/guc_hooks.h" |
| 104 |
#include "utils/injection_point.h" |
| 105 |
#include "utils/lsyscache.h" |
| 106 |
#include "utils/memutils.h" |
| 107 |
#include "utils/ps_status.h" |
| 108 |
#include "utils/rel.h" |
| 109 |
#include "utils/snapmgr.h" |
| 110 |
#include "utils/syscache.h" |
| 111 |
#include "utils/timeout.h" |
| 112 |
#include "utils/timestamp.h" |
| 113 |
|
| 114 |
|
| 115 |
/* |
| 116 |
* GUC parameters |
| 117 |
*/ |
| 118 |
bool autovacuum_start_daemon = false; |
| 119 |
int autovacuum_worker_slots; |
| 120 |
int autovacuum_max_workers; |
| 121 |
int autovacuum_work_mem = -1; |
| 122 |
int autovacuum_naptime; |
| 123 |
int autovacuum_vac_thresh; |
| 124 |
int autovacuum_vac_max_thresh; |
| 125 |
double autovacuum_vac_scale; |
| 126 |
int autovacuum_vac_ins_thresh; |
| 127 |
double autovacuum_vac_ins_scale; |
| 128 |
int autovacuum_anl_thresh; |
| 129 |
double autovacuum_anl_scale; |
| 130 |
int autovacuum_freeze_max_age; |
| 131 |
int autovacuum_multixact_freeze_max_age; |
| 132 |
|
| 133 |
double autovacuum_vac_cost_delay; |
| 134 |
int autovacuum_vac_cost_limit; |
| 135 |
|
| 136 |
int Log_autovacuum_min_duration = 600000; |
| 137 |
|
| 138 |
/* the minimum allowed time between two awakenings of the launcher */ |
| 139 |
#define MIN_AUTOVAC_SLEEPTIME 100.0 /* milliseconds */ |
| 140 |
#define MAX_AUTOVAC_SLEEPTIME 300 /* seconds */ |
| 141 |
|
| 142 |
/* |
| 143 |
* Variables to save the cost-related storage parameters for the current |
| 144 |
* relation being vacuumed by this autovacuum worker. Using these, we can |
| 145 |
* ensure we don't overwrite the values of vacuum_cost_delay and |
| 146 |
* vacuum_cost_limit after reloading the configuration file. They are |
| 147 |
* initialized to "invalid" values to indicate that no cost-related storage |
| 148 |
* parameters were specified and will be set in do_autovacuum() after checking |
| 149 |
* the storage parameters in table_recheck_autovac(). |
| 150 |
*/ |
| 151 |
static double av_storage_param_cost_delay = -1; |
| 152 |
static int av_storage_param_cost_limit = -1; |
| 153 |
|
| 154 |
/* Flags set by signal handlers */ |
| 155 |
static volatile sig_atomic_t got_SIGUSR2 = false; |
| 156 |
|
| 157 |
/* Comparison points for determining whether freeze_max_age is exceeded */ |
| 158 |
static TransactionId recentXid; |
| 159 |
static MultiXactId recentMulti; |
| 160 |
|
| 161 |
/* Default freeze ages to use for autovacuum (varies by database) */ |
| 162 |
static int default_freeze_min_age; |
| 163 |
static int default_freeze_table_age; |
| 164 |
static int default_multixact_freeze_min_age; |
| 165 |
static int default_multixact_freeze_table_age; |
| 166 |
|
| 167 |
/* Memory context for long-lived data */ |
| 168 |
static MemoryContext AutovacMemCxt; |
| 169 |
|
| 170 |
/* struct to keep track of databases in launcher */ |
| 171 |
typedef struct avl_dbase |
| 172 |
{ |
| 173 |
Oid adl_datid; /* hash key -- must be first */ |
| 174 |
TimestampTz adl_next_worker; |
| 175 |
int adl_score; |
| 176 |
dlist_node adl_node; |
| 177 |
} avl_dbase; |
| 178 |
|
| 179 |
/* struct to keep track of databases in worker */ |
| 180 |
typedef struct avw_dbase |
| 181 |
{ |
| 182 |
Oid adw_datid; |
| 183 |
char *adw_name; |
| 184 |
TransactionId adw_frozenxid; |
| 185 |
MultiXactId adw_minmulti; |
| 186 |
PgStat_StatDBEntry *adw_entry; |
| 187 |
} avw_dbase; |
| 188 |
|
| 189 |
/* struct to keep track of tables to vacuum and/or analyze, in 1st pass */ |
| 190 |
typedef struct av_relation |
| 191 |
{ |
| 192 |
Oid ar_toastrelid; /* hash key - must be first */ |
| 193 |
Oid ar_relid; |
| 194 |
bool ar_hasrelopts; |
| 195 |
AutoVacOpts ar_reloptions; /* copy of AutoVacOpts from the main table's |
| 196 |
* reloptions, or NULL if none */ |
| 197 |
} av_relation; |
| 198 |
|
| 199 |
/* struct to keep track of tables to vacuum and/or analyze, after rechecking */ |
| 200 |
typedef struct autovac_table |
| 201 |
{ |
| 202 |
Oid at_relid; |
| 203 |
VacuumParams at_params; |
| 204 |
double at_storage_param_vac_cost_delay; |
| 205 |
int at_storage_param_vac_cost_limit; |
| 206 |
bool at_dobalance; |
| 207 |
bool at_sharedrel; |
| 208 |
char *at_relname; |
| 209 |
char *at_nspname; |
| 210 |
char *at_datname; |
| 211 |
} autovac_table; |
| 212 |
|
| 213 |
/*------------- |
| 214 |
* This struct holds information about a single worker's whereabouts. We keep |
| 215 |
* an array of these in shared memory, sized according to |
| 216 |
* autovacuum_worker_slots. |
| 217 |
* |
| 218 |
* wi_links entry into free list or running list |
| 219 |
* wi_dboid OID of the database this worker is supposed to work on |
| 220 |
* wi_tableoid OID of the table currently being vacuumed, if any |
| 221 |
* wi_sharedrel flag indicating whether table is marked relisshared |
| 222 |
* wi_proc pointer to PGPROC of the running worker, NULL if not started |
| 223 |
* wi_launchtime Time at which this worker was launched |
| 224 |
* wi_dobalance Whether this worker should be included in balance calculations |
| 225 |
* |
| 226 |
* All fields are protected by AutovacuumLock, except for wi_tableoid and |
| 227 |
* wi_sharedrel which are protected by AutovacuumScheduleLock (note these |
| 228 |
* two fields are read-only for everyone except that worker itself). |
| 229 |
*------------- |
| 230 |
*/ |
| 231 |
typedef struct WorkerInfoData |
| 232 |
{ |
| 233 |
dlist_node wi_links; |
| 234 |
Oid wi_dboid; |
| 235 |
Oid wi_tableoid; |
| 236 |
PGPROC *wi_proc; |
| 237 |
TimestampTz wi_launchtime; |
| 238 |
pg_atomic_flag wi_dobalance; |
| 239 |
bool wi_sharedrel; |
| 240 |
} WorkerInfoData; |
| 241 |
|
| 242 |
typedef struct WorkerInfoData *WorkerInfo; |
| 243 |
|
| 244 |
/* |
| 245 |
* Possible signals received by the launcher from remote processes. These are |
| 246 |
* stored atomically in shared memory so that other processes can set them |
| 247 |
* without locking. |
| 248 |
*/ |
| 249 |
typedef enum |
| 250 |
{ |
| 251 |
AutoVacForkFailed, /* failed trying to start a worker */ |
| 252 |
AutoVacRebalance, /* rebalance the cost limits */ |
| 253 |
} AutoVacuumSignal; |
| 254 |
|
| 255 |
#define AutoVacNumSignals (AutoVacRebalance + 1) |
| 256 |
|
| 257 |
/* |
| 258 |
* Autovacuum workitem array, stored in AutoVacuumShmem->av_workItems. This |
| 259 |
* list is mostly protected by AutovacuumLock, except that if an item is |
| 260 |
* marked 'active' other processes must not modify the work-identifying |
| 261 |
* members. |
| 262 |
*/ |
| 263 |
typedef struct AutoVacuumWorkItem |
| 264 |
{ |
| 265 |
AutoVacuumWorkItemType avw_type; |
| 266 |
bool avw_used; /* below data is valid */ |
| 267 |
bool avw_active; /* being processed */ |
| 268 |
Oid avw_database; |
| 269 |
Oid avw_relation; |
| 270 |
BlockNumber avw_blockNumber; |
| 271 |
} AutoVacuumWorkItem; |
| 272 |
|
| 273 |
#define NUM_WORKITEMS 256 |
| 274 |
|
| 275 |
/*------------- |
| 276 |
* The main autovacuum shmem struct. On shared memory we store this main |
| 277 |
* struct and the array of WorkerInfo structs. This struct keeps: |
| 278 |
* |
| 279 |
* av_signal set by other processes to indicate various conditions |
| 280 |
* av_launcherpid the PID of the autovacuum launcher |
| 281 |
* av_freeWorkers the WorkerInfo freelist |
| 282 |
* av_runningWorkers the WorkerInfo non-free queue |
| 283 |
* av_startingWorker pointer to WorkerInfo currently being started (cleared by |
| 284 |
* the worker itself as soon as it's up and running) |
| 285 |
* av_workItems work item array |
| 286 |
* av_nworkersForBalance the number of autovacuum workers to use when |
| 287 |
* calculating the per worker cost limit |
| 288 |
* |
| 289 |
* This struct is protected by AutovacuumLock, except for av_signal and parts |
| 290 |
* of the worker list (see above). |
| 291 |
*------------- |
| 292 |
*/ |
| 293 |
typedef struct |
| 294 |
{ |
| 295 |
sig_atomic_t av_signal[AutoVacNumSignals]; |
| 296 |
pid_t av_launcherpid; |
| 297 |
dclist_head av_freeWorkers; |
| 298 |
dlist_head av_runningWorkers; |
| 299 |
WorkerInfo av_startingWorker; |
| 300 |
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]; |
| 301 |
pg_atomic_uint32 av_nworkersForBalance; |
| 302 |
} AutoVacuumShmemStruct; |
| 303 |
|
| 304 |
static AutoVacuumShmemStruct *AutoVacuumShmem; |
| 305 |
|
| 306 |
/* |
| 307 |
* the database list (of avl_dbase elements) in the launcher, and the context |
| 308 |
* that contains it |
| 309 |
*/ |
| 310 |
static dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList); |
| 311 |
static MemoryContext DatabaseListCxt = NULL; |
| 312 |
|
| 313 |
/* Pointer to my own WorkerInfo, valid on each worker */ |
| 314 |
static WorkerInfo MyWorkerInfo = NULL; |
| 315 |
|
| 316 |
/* PID of launcher, valid only in worker while shutting down */ |
| 317 |
int AutovacuumLauncherPid = 0; |
| 318 |
|
| 319 |
static Oid do_start_worker(void); |
| 320 |
static void ProcessAutoVacLauncherInterrupts(void); |
| 321 |
pg_noreturn static void AutoVacLauncherShutdown(void); |
| 322 |
static void launcher_determine_sleep(bool canlaunch, bool recursing, |
| 323 |
struct timeval *nap); |
| 324 |
static void launch_worker(TimestampTz now); |
| 325 |
static List *get_database_list(void); |
| 326 |
static void rebuild_database_list(Oid newdb); |
| 327 |
static int db_comparator(const void *a, const void *b); |
| 328 |
static void autovac_recalculate_workers_for_balance(void); |
| 329 |
|
| 330 |
static void do_autovacuum(void); |
| 331 |
static void FreeWorkerInfo(int code, Datum arg); |
| 332 |
|
| 333 |
static autovac_table *table_recheck_autovac(Oid relid, HTAB *table_toast_map, |
| 334 |
TupleDesc pg_class_desc, |
| 335 |
int effective_multixact_freeze_max_age); |
| 336 |
static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts, |
| 337 |
Form_pg_class classForm, |
| 338 |
int effective_multixact_freeze_max_age, |
| 339 |
bool *dovacuum, bool *doanalyze, bool *wraparound); |
| 340 |
static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts, |
| 341 |
Form_pg_class classForm, |
| 342 |
PgStat_StatTabEntry *tabentry, |
| 343 |
int effective_multixact_freeze_max_age, |
| 344 |
bool *dovacuum, bool *doanalyze, bool *wraparound); |
| 345 |
|
| 346 |
static void autovacuum_do_vac_analyze(autovac_table *tab, |
| 347 |
BufferAccessStrategy bstrategy); |
| 348 |
static AutoVacOpts *extract_autovac_opts(HeapTuple tup, |
| 349 |
TupleDesc pg_class_desc); |
| 350 |
static void perform_work_item(AutoVacuumWorkItem *workitem); |
| 351 |
static void autovac_report_activity(autovac_table *tab); |
| 352 |
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, |
| 353 |
const char *nspname, const char *relname); |
| 354 |
static void avl_sigusr2_handler(SIGNAL_ARGS); |
| 355 |
static bool av_worker_available(void); |
| 356 |
static void check_av_worker_gucs(void); |
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
/******************************************************************** |
| 361 |
* AUTOVACUUM LAUNCHER CODE |
| 362 |
********************************************************************/ |
| 363 |
|
| 364 |
/* |
| 365 |
* Main entry point for the autovacuum launcher process. |
| 366 |
*/ |
| 367 |
void |
| 368 |
AutoVacLauncherMain(const void *startup_data, size_t startup_data_len) |
| 369 |
{ |
| 370 |
sigjmp_buf local_sigjmp_buf; |
| 371 |
|
| 372 |
Assert(startup_data_len == 0); |
| 373 |
|
| 374 |
/* Release postmaster's working memory context */ |
| 375 |
if (PostmasterContext) |
| 376 |
{ |
| 377 |
MemoryContextDelete(PostmasterContext); |
| 378 |
PostmasterContext = NULL; |
| 379 |
} |
| 380 |
|
| 381 |
MyBackendType = B_AUTOVAC_LAUNCHER; |
| 382 |
init_ps_display(NULL); |
| 383 |
|
| 384 |
ereport(DEBUG1, |
| 385 |
(errmsg_internal("autovacuum launcher started"))); |
| 386 |
|
| 387 |
if (PostAuthDelay) |
| 388 |
pg_usleep(PostAuthDelay * 1000000L); |
| 389 |
|
| 390 |
Assert(GetProcessingMode() == InitProcessing); |
| 391 |
|
| 392 |
/* |
| 393 |
* Set up signal handlers. We operate on databases much like a regular |
| 394 |
* backend, so we use the same signal handling. See equivalent code in |
| 395 |
* tcop/postgres.c. |
| 396 |
*/ |
| 397 |
pqsignal(SIGHUP, SignalHandlerForConfigReload); |
| 398 |
pqsignal(SIGINT, StatementCancelHandler); |
| 399 |
pqsignal(SIGTERM, SignalHandlerForShutdownRequest); |
| 400 |
/* SIGQUIT handler was already set up by InitPostmasterChild */ |
| 401 |
|
| 402 |
InitializeTimeouts(); /* establishes SIGALRM handler */ |
| 403 |
|
| 404 |
pqsignal(SIGPIPE, SIG_IGN); |
| 405 |
pqsignal(SIGUSR1, procsignal_sigusr1_handler); |
| 406 |
pqsignal(SIGUSR2, avl_sigusr2_handler); |
| 407 |
pqsignal(SIGFPE, FloatExceptionHandler); |
| 408 |
pqsignal(SIGCHLD, SIG_DFL); |
| 409 |
|
| 410 |
/* |
| 411 |
* Create a per-backend PGPROC struct in shared memory. We must do this |
| 412 |
* before we can use LWLocks or access any shared memory. |
| 413 |
*/ |
| 414 |
InitProcess(); |
| 415 |
|
| 416 |
/* Early initialization */ |
| 417 |
BaseInit(); |
| 418 |
|
| 419 |
InitPostgres(NULL, InvalidOid, NULL, InvalidOid, 0, NULL); |
| 420 |
|
| 421 |
SetProcessingMode(NormalProcessing); |
| 422 |
|
| 423 |
/* |
| 424 |
* Create a memory context that we will do all our work in. We do this so |
| 425 |
* that we can reset the context during error recovery and thereby avoid |
| 426 |
* possible memory leaks. |
| 427 |
*/ |
| 428 |
AutovacMemCxt = AllocSetContextCreate(TopMemoryContext, |
| 429 |
"Autovacuum Launcher", |
| 430 |
ALLOCSET_DEFAULT_SIZES); |
| 431 |
MemoryContextSwitchTo(AutovacMemCxt); |
| 432 |
|
| 433 |
/* |
| 434 |
* If an exception is encountered, processing resumes here. |
| 435 |
* |
| 436 |
* This code is a stripped down version of PostgresMain error recovery. |
| 437 |
* |
| 438 |
* Note that we use sigsetjmp(..., 1), so that the prevailing signal mask |
| 439 |
* (to wit, BlockSig) will be restored when longjmp'ing to here. Thus, |
| 440 |
* signals other than SIGQUIT will be blocked until we complete error |
| 441 |
* recovery. It might seem that this policy makes the HOLD_INTERRUPTS() |
| 442 |
* call redundant, but it is not since InterruptPending might be set |
| 443 |
* already. |
| 444 |
*/ |
| 445 |
if (sigsetjmp(local_sigjmp_buf, 1) != 0) |
| 446 |
{ |
| 447 |
/* since not using PG_TRY, must reset error stack by hand */ |
| 448 |
error_context_stack = NULL; |
| 449 |
|
| 450 |
/* Prevents interrupts while cleaning up */ |
| 451 |
HOLD_INTERRUPTS(); |
| 452 |
|
| 453 |
/* Forget any pending QueryCancel or timeout request */ |
| 454 |
disable_all_timeouts(false); |
| 455 |
QueryCancelPending = false; /* second to avoid race condition */ |
| 456 |
|
| 457 |
/* Report the error to the server log */ |
| 458 |
EmitErrorReport(); |
| 459 |
|
| 460 |
/* Abort the current transaction in order to recover */ |
| 461 |
AbortCurrentTransaction(); |
| 462 |
|
| 463 |
/* |
| 464 |
* Release any other resources, for the case where we were not in a |
| 465 |
* transaction. |
| 466 |
*/ |
| 467 |
LWLockReleaseAll(); |
| 468 |
pgstat_report_wait_end(); |
| 469 |
pgaio_error_cleanup(); |
| 470 |
UnlockBuffers(); |
| 471 |
/* this is probably dead code, but let's be safe: */ |
| 472 |
if (AuxProcessResourceOwner) |
| 473 |
ReleaseAuxProcessResources(false); |
| 474 |
AtEOXact_Buffers(false); |
| 475 |
AtEOXact_SMgr(); |
| 476 |
AtEOXact_Files(false); |
| 477 |
AtEOXact_HashTables(false); |
| 478 |
|
| 479 |
/* |
| 480 |
* Now return to normal top-level context and clear ErrorContext for |
| 481 |
* next time. |
| 482 |
*/ |
| 483 |
MemoryContextSwitchTo(AutovacMemCxt); |
| 484 |
FlushErrorState(); |
| 485 |
|
| 486 |
/* Flush any leaked data in the top-level context */ |
| 487 |
MemoryContextReset(AutovacMemCxt); |
| 488 |
|
| 489 |
/* don't leave dangling pointers to freed memory */ |
| 490 |
DatabaseListCxt = NULL; |
| 491 |
dlist_init(&DatabaseList); |
| 492 |
|
| 493 |
/* Now we can allow interrupts again */ |
| 494 |
RESUME_INTERRUPTS(); |
| 495 |
|
| 496 |
/* if in shutdown mode, no need for anything further; just go away */ |
| 497 |
if (ShutdownRequestPending) |
| 498 |
AutoVacLauncherShutdown(); |
| 499 |
|
| 500 |
/* |
| 501 |
* Sleep at least 1 second after any error. We don't want to be |
| 502 |
* filling the error logs as fast as we can. |
| 503 |
*/ |
| 504 |
pg_usleep(1000000L); |
| 505 |
} |
| 506 |
|
| 507 |
/* We can now handle ereport(ERROR) */ |
| 508 |
PG_exception_stack = &local_sigjmp_buf; |
| 509 |
|
| 510 |
/* must unblock signals before calling rebuild_database_list */ |
| 511 |
sigprocmask(SIG_SETMASK, &UnBlockSig, NULL); |
| 512 |
|
| 513 |
/* |
| 514 |
* Set always-secure search path. Launcher doesn't connect to a database, |
| 515 |
* so this has no effect. |
| 516 |
*/ |
| 517 |
SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE); |
| 518 |
|
| 519 |
/* |
| 520 |
* Force zero_damaged_pages OFF in the autovac process, even if it is set |
| 521 |
* in postgresql.conf. We don't really want such a dangerous option being |
| 522 |
* applied non-interactively. |
| 523 |
*/ |
| 524 |
SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE); |
| 525 |
|
| 526 |
/* |
| 527 |
* Force settable timeouts off to avoid letting these settings prevent |
| 528 |
* regular maintenance from being executed. |
| 529 |
*/ |
| 530 |
SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE); |
| 531 |
SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE); |
| 532 |
SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE); |
| 533 |
SetConfigOption("idle_in_transaction_session_timeout", "0", |
| 534 |
PGC_SUSET, PGC_S_OVERRIDE); |
| 535 |
|
| 536 |
/* |
| 537 |
* Force default_transaction_isolation to READ COMMITTED. We don't want |
| 538 |
* to pay the overhead of serializable mode, nor add any risk of causing |
| 539 |
* deadlocks or delaying other transactions. |
| 540 |
*/ |
| 541 |
SetConfigOption("default_transaction_isolation", "read committed", |
| 542 |
PGC_SUSET, PGC_S_OVERRIDE); |
| 543 |
|
| 544 |
/* |
| 545 |
* Even when system is configured to use a different fetch consistency, |
| 546 |
* for autovac we always want fresh stats. |
| 547 |
*/ |
| 548 |
SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE); |
| 549 |
|
| 550 |
/* |
| 551 |
* In emergency mode, just start a worker (unless shutdown was requested) |
| 552 |
* and go away. |
| 553 |
*/ |
| 554 |
if (!AutoVacuumingActive()) |
| 555 |
{ |
| 556 |
if (!ShutdownRequestPending) |
| 557 |
do_start_worker(); |
| 558 |
proc_exit(0); /* done */ |
| 559 |
} |
| 560 |
|
| 561 |
AutoVacuumShmem->av_launcherpid = MyProcPid; |
| 562 |
|
| 563 |
/* |
| 564 |
* Create the initial database list. The invariant we want this list to |
| 565 |
* keep is that it's ordered by decreasing next_time. As soon as an entry |
| 566 |
* is updated to a higher time, it will be moved to the front (which is |
| 567 |
* correct because the only operation is to add autovacuum_naptime to the |
| 568 |
* entry, and time always increases). |
| 569 |
*/ |
| 570 |
rebuild_database_list(InvalidOid); |
| 571 |
|
| 572 |
/* loop until shutdown request */ |
| 573 |
while (!ShutdownRequestPending) |
| 574 |
{ |
| 575 |
struct timeval nap; |
| 576 |
TimestampTz current_time = 0; |
| 577 |
bool can_launch; |
| 578 |
|
| 579 |
/* |
| 580 |
* This loop is a bit different from the normal use of WaitLatch, |
| 581 |
* because we'd like to sleep before the first launch of a child |
| 582 |
* process. So it's WaitLatch, then ResetLatch, then check for |
| 583 |
* wakening conditions. |
| 584 |
*/ |
| 585 |
|
| 586 |
launcher_determine_sleep(av_worker_available(), false, &nap); |
| 587 |
|
| 588 |
/* |
| 589 |
* Wait until naptime expires or we get some type of signal (all the |
| 590 |
* signal handlers will wake us by calling SetLatch). |
| 591 |
*/ |
| 592 |
(void) WaitLatch(MyLatch, |
| 593 |
WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, |
| 594 |
(nap.tv_sec * 1000L) + (nap.tv_usec / 1000L), |
| 595 |
WAIT_EVENT_AUTOVACUUM_MAIN); |
| 596 |
|
| 597 |
ResetLatch(MyLatch); |
| 598 |
|
| 599 |
ProcessAutoVacLauncherInterrupts(); |
| 600 |
|
| 601 |
/* |
| 602 |
* a worker finished, or postmaster signaled failure to start a worker |
| 603 |
*/ |
| 604 |
if (got_SIGUSR2) |
| 605 |
{ |
| 606 |
got_SIGUSR2 = false; |
| 607 |
|
| 608 |
/* rebalance cost limits, if needed */ |
| 609 |
if (AutoVacuumShmem->av_signal[AutoVacRebalance]) |
| 610 |
{ |
| 611 |
LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); |
| 612 |
AutoVacuumShmem->av_signal[AutoVacRebalance] = false; |
| 613 |
autovac_recalculate_workers_for_balance(); |
| 614 |
LWLockRelease(AutovacuumLock); |
| 615 |
} |
| 616 |
|
| 617 |
if (AutoVacuumShmem->av_signal[AutoVacForkFailed]) |
| 618 |
{ |
| 619 |
/* |
| 620 |
* If the postmaster failed to start a new worker, we sleep |
| 621 |
* for a little while and resend the signal. The new worker's |
| 622 |
* state is still in memory, so this is sufficient. After |
| 623 |
* that, we restart the main loop. |
| 624 |
* |
| 625 |
* XXX should we put a limit to the number of times we retry? |
| 626 |
* I don't think it makes much sense, because a future start |
| 627 |
* of a worker will continue to fail in the same way. |
| 628 |
*/ |
| 629 |
AutoVacuumShmem->av_signal[AutoVacForkFailed] = false; |
| 630 |
pg_usleep(1000000L); /* 1s */ |
| 631 |
SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER); |
| 632 |
continue; |
| 633 |
} |
| 634 |
} |
| 635 |
|
| 636 |
/* |
| 637 |
* There are some conditions that we need to check before trying to |
| 638 |
* start a worker. First, we need to make sure that there is a worker |
| 639 |
* slot available. Second, we need to make sure that no other worker |
| 640 |
* failed while starting up. |
| 641 |
*/ |
| 642 |
|
| 643 |
current_time = GetCurrentTimestamp(); |
| 644 |
LWLockAcquire(AutovacuumLock, LW_SHARED); |
| 645 |
|
| 646 |
can_launch = av_worker_available(); |
| 647 |
|
| 648 |
if (AutoVacuumShmem->av_startingWorker != NULL) |
| 649 |
{ |
| 650 |
int waittime; |
| 651 |
WorkerInfo worker = AutoVacuumShmem->av_startingWorker; |
| 652 |
|
| 653 |
/* |
| 654 |
* We can't launch another worker when another one is still |
| 655 |
* starting up (or failed while doing so), so just sleep for a bit |
| 656 |
* more; that worker will wake us up again as soon as it's ready. |
| 657 |
* We will only wait autovacuum_naptime seconds (up to a maximum |
| 658 |
* of 60 seconds) for this to happen however. Note that failure |
| 659 |
* to connect to a particular database is not a problem here, |
| 660 |
* because the worker removes itself from the startingWorker |
| 661 |
* pointer before trying to connect. Problems detected by the |
| 662 |
* postmaster (like fork() failure) are also reported and handled |
| 663 |
* differently. The only problems that may cause this code to |
| 664 |
* fire are errors in the earlier sections of AutoVacWorkerMain, |
| 665 |
* before the worker removes the WorkerInfo from the |
| 666 |
* startingWorker pointer. |
| 667 |
*/ |
| 668 |
waittime = Min(autovacuum_naptime, 60) * 1000; |
| 669 |
if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time, |
| 670 |
waittime)) |
| 671 |
{ |
| 672 |
LWLockRelease(AutovacuumLock); |
| 673 |
LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); |
| 674 |
|
| 675 |
/* |
| 676 |
* No other process can put a worker in starting mode, so if |
| 677 |
* startingWorker is still INVALID after exchanging our lock, |
| 678 |
* we assume it's the same one we saw above (so we don't |
| 679 |
* recheck the launch time). |
| 680 |
*/ |
| 681 |
if (AutoVacuumShmem->av_startingWorker != NULL) |
| 682 |
{ |
| 683 |
worker = AutoVacuumShmem->av_startingWorker; |
| 684 |
worker->wi_dboid = InvalidOid; |
| 685 |
worker->wi_tableoid = InvalidOid; |
| 686 |
worker->wi_sharedrel = false; |
| 687 |
worker->wi_proc = NULL; |
| 688 |
worker->wi_launchtime = 0; |
| 689 |
dclist_push_head(&AutoVacuumShmem->av_freeWorkers, |
| 690 |
&worker->wi_links); |
| 691 |
AutoVacuumShmem->av_startingWorker = NULL; |
| 692 |
ereport(WARNING, |
| 693 |
errmsg("autovacuum worker took too long to start; canceled")); |
| 694 |
} |
| 695 |
} |
| 696 |
else |
| 697 |
can_launch = false; |
| 698 |
} |
| 699 |
LWLockRelease(AutovacuumLock); /* either shared or exclusive */ |
| 700 |
|
| 701 |
/* if we can't do anything, just go back to sleep */ |
| 702 |
if (!can_launch) |
| 703 |
continue; |
| 704 |
|
| 705 |
/* We're OK to start a new worker */ |
| 706 |
|
| 707 |
if (dlist_is_empty(&DatabaseList)) |
| 708 |
{ |
| 709 |
/* |
| 710 |
* Special case when the list is empty: start a worker right away. |
| 711 |
* This covers the initial case, when no database is in pgstats |
| 712 |
* (thus the list is empty). Note that the constraints in |
| 713 |
* launcher_determine_sleep keep us from starting workers too |
| 714 |
* quickly (at most once every autovacuum_naptime when the list is |
| 715 |
* empty). |
| 716 |
*/ |
| 717 |
launch_worker(current_time); |
| 718 |
} |
| 719 |
else |
| 720 |
{ |
| 721 |
/* |
| 722 |
* because rebuild_database_list constructs a list with most |
| 723 |
* distant adl_next_worker first, we obtain our database from the |
| 724 |
* tail of the list. |
| 725 |
*/ |
| 726 |
avl_dbase *avdb; |
| 727 |
|
| 728 |
avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList); |
| 729 |
|
| 730 |
/* |
| 731 |
* launch a worker if next_worker is right now or it is in the |
| 732 |
* past |
| 733 |
*/ |
| 734 |
if (TimestampDifferenceExceeds(avdb->adl_next_worker, |
| 735 |
current_time, 0)) |
| 736 |
launch_worker(current_time); |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
AutoVacLauncherShutdown(); |
| 741 |
} |
| 742 |
|
| 743 |
/* |
| 744 |
* Process any new interrupts. |
| 745 |
*/ |
| 746 |
static void |
| 747 |
ProcessAutoVacLauncherInterrupts(void) |
| 748 |
{ |
| 749 |
/* the normal shutdown case */ |
| 750 |
if (ShutdownRequestPending) |
| 751 |
AutoVacLauncherShutdown(); |
| 752 |
|
| 753 |
if (ConfigReloadPending) |
| 754 |
{ |
| 755 |
int autovacuum_max_workers_prev = autovacuum_max_workers; |
| 756 |
|
| 757 |
ConfigReloadPending = false; |
| 758 |
ProcessConfigFile(PGC_SIGHUP); |
| 759 |
|
| 760 |
/* shutdown requested in config file? */ |
| 761 |
if (!AutoVacuumingActive()) |
| 762 |
AutoVacLauncherShutdown(); |
| 763 |
|
| 764 |
/* |
| 765 |
* If autovacuum_max_workers changed, emit a WARNING if |
| 766 |
* autovacuum_worker_slots < autovacuum_max_workers. If it didn't |
| 767 |
* change, skip this to avoid too many repeated log messages. |
| 768 |
*/ |
| 769 |
if (autovacuum_max_workers_prev != autovacuum_max_workers) |
| 770 |
check_av_worker_gucs(); |
| 771 |
|
| 772 |
/* rebuild the list in case the naptime changed */ |
| 773 |
rebuild_database_list(InvalidOid); |
| 774 |
} |
| 775 |
|
| 776 |
/* Process barrier events */ |
| 777 |
if (ProcSignalBarrierPending) |
| 778 |
ProcessProcSignalBarrier(); |
| 779 |
|
| 780 |
/* Perform logging of memory contexts of this process */ |
| 781 |
if (LogMemoryContextPending) |
| 782 |
ProcessLogMemoryContextInterrupt(); |
| 783 |
|
| 784 |
/* Process sinval catchup interrupts that happened while sleeping */ |
| 785 |
ProcessCatchupInterrupt(); |
| 786 |
} |
| 787 |
|
| 788 |
/* |
| 789 |
* Perform a normal exit from the autovac launcher. |
| 790 |
*/ |
| 791 |
static void |
| 792 |
AutoVacLauncherShutdown(void) |
| 793 |
{ |
| 794 |
ereport(DEBUG1, |
| 795 |
(errmsg_internal("autovacuum launcher shutting down"))); |
| 796 |
AutoVacuumShmem->av_launcherpid = 0; |
| 797 |
|
| 798 |
proc_exit(0); /* done */ |
| 799 |
} |
| 800 |
|
| 801 |
/* |
| 802 |
* Determine the time to sleep, based on the database list. |
| 803 |
* |
| 804 |
* The "canlaunch" parameter indicates whether we can start a worker right now, |
| 805 |
* for example due to the workers being all busy. If this is false, we will |
| 806 |
* cause a long sleep, which will be interrupted when a worker exits. |
| 807 |
*/ |
| 808 |
static void |
| 809 |
launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap) |
| 810 |
{ |
| 811 |
/* |
| 812 |
* We sleep until the next scheduled vacuum. We trust that when the |
| 813 |
* database list was built, care was taken so that no entries have times |
| 814 |
* in the past; if the first entry has too close a next_worker value, or a |
| 815 |
* time in the past, we will sleep a small nominal time. |
| 816 |
*/ |
| 817 |
if (!canlaunch) |
| 818 |
{ |
| 819 |
nap->tv_sec = autovacuum_naptime; |
| 820 |
nap->tv_usec = 0; |
| 821 |
} |
| 822 |
else if (!dlist_is_empty(&DatabaseList)) |
| 823 |
{ |
| 824 |
TimestampTz current_time = GetCurrentTimestamp(); |
| 825 |
TimestampTz next_wakeup; |
| 826 |
avl_dbase *avdb; |
| 827 |
long secs; |
| 828 |
int usecs; |
| 829 |
|
| 830 |
avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList); |
| 831 |
|
| 832 |
next_wakeup = avdb->adl_next_worker; |
| 833 |
TimestampDifference(current_time, next_wakeup, &secs, &usecs); |
| 834 |
|
| 835 |
nap->tv_sec = secs; |
| 836 |
nap->tv_usec = usecs; |
| 837 |
} |
| 838 |
else |
| 839 |
{ |
| 840 |
/* list is empty, sleep for whole autovacuum_naptime seconds */ |
| 841 |
nap->tv_sec = autovacuum_naptime; |
| 842 |
nap->tv_usec = 0; |
| 843 |
} |
| 844 |
|
| 845 |
/* |
| 846 |
* If the result is exactly zero, it means a database had an entry with |
| 847 |
* time in the past. Rebuild the list so that the databases are evenly |
| 848 |
* distributed again, and recalculate the time to sleep. This can happen |
| 849 |
* if there are more tables needing vacuum than workers, and they all take |
| 850 |
* longer to vacuum than autovacuum_naptime. |
| 851 |
* |
| 852 |
* We only recurse once. rebuild_database_list should always return times |
| 853 |
* in the future, but it seems best not to trust too much on that. |
| 854 |
*/ |
| 855 |
if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing) |
| 856 |
{ |
| 857 |
rebuild_database_list(InvalidOid); |
| 858 |
launcher_determine_sleep(canlaunch, true, nap); |
| 859 |
return; |
| 860 |
} |
| 861 |
|
| 862 |
/* The smallest time we'll allow the launcher to sleep. */ |
| 863 |
if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000) |
| 864 |
{ |
| 865 |
nap->tv_sec = 0; |
| 866 |
nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000; |
| 867 |
} |
| 868 |
|
| 869 |
/* |
| 870 |
* If the sleep time is too large, clamp it to an arbitrary maximum (plus |
| 871 |
* any fractional seconds, for simplicity). This avoids an essentially |
| 872 |
* infinite sleep in strange cases like the system clock going backwards a |
| 873 |
* few years. |
| 874 |
*/ |
| 875 |
if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME) |
| 876 |
nap->tv_sec = MAX_AUTOVAC_SLEEPTIME; |
| 877 |
} |
| 878 |
|
| 879 |
/* |
| 880 |
* Build an updated DatabaseList. It must only contain databases that appear |
| 881 |
* in pgstats, and must be sorted by next_worker from highest to lowest, |
| 882 |
* distributed regularly across the next autovacuum_naptime interval. |
| 883 |
* |
| 884 |
* Receives the Oid of the database that made this list be generated (we call |
| 885 |
* this the "new" database, because when the database was already present on |
| 886 |
* the list, we expect that this function is not called at all). The |
| 887 |
* preexisting list, if any, will be used to preserve the order of the |
| 888 |
* databases in the autovacuum_naptime period. The new database is put at the |
| 889 |
* end of the interval. The actual values are not saved, which should not be |
| 890 |
* much of a problem. |
| 891 |
*/ |
| 892 |
static void |
| 893 |
rebuild_database_list(Oid newdb) |
| 894 |
{ |
| 895 |
List *dblist; |
| 896 |
ListCell *cell; |
| 897 |
MemoryContext newcxt; |
| 898 |
MemoryContext oldcxt; |
| 899 |
MemoryContext tmpcxt; |
| 900 |
HASHCTL hctl; |
| 901 |
int score; |
| 902 |
int nelems; |
| 903 |
HTAB *dbhash; |
| 904 |
dlist_iter iter; |
| 905 |
|
| 906 |
newcxt = AllocSetContextCreate(AutovacMemCxt, |
| 907 |
"Autovacuum database list", |
| 908 |
ALLOCSET_DEFAULT_SIZES); |
| 909 |
tmpcxt = AllocSetContextCreate(newcxt, |
| 910 |
"Autovacuum database list (tmp)", |
| 911 |
ALLOCSET_DEFAULT_SIZES); |
| 912 |
oldcxt = MemoryContextSwitchTo(tmpcxt); |
| 913 |
|
| 914 |
/* |
| 915 |
* Implementing this is not as simple as it sounds, because we need to put |
| 916 |
* the new database at the end of the list; next the databases that were |
| 917 |
* already on the list, and finally (at the tail of the list) all the |
| 918 |
* other databases that are not on the existing list. |
| 919 |
* |
| 920 |
* To do this, we build an empty hash table of scored databases. We will |
| 921 |
* start with the lowest score (zero) for the new database, then |
| 922 |
* increasing scores for the databases in the existing list, in order, and |
| 923 |
* lastly increasing scores for all databases gotten via |
| 924 |
* get_database_list() that are not already on the hash. |
| 925 |
* |
| 926 |
* Then we will put all the hash elements into an array, sort the array by |
| 927 |
* score, and finally put the array elements into the new doubly linked |
| 928 |
* list. |
| 929 |
*/ |
| 930 |
hctl.keysize = sizeof(Oid); |
| 931 |
hctl.entrysize = sizeof(avl_dbase); |
| 932 |
hctl.hcxt = tmpcxt; |
| 933 |
dbhash = hash_create("autovacuum db hash", 20, &hctl, /* magic number here |
| 934 |
* FIXME */ |
| 935 |
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); |
| 936 |
|
| 937 |
/* start by inserting the new database */ |
| 938 |
score = 0; |
| 939 |
if (OidIsValid(newdb)) |
| 940 |
{ |
| 941 |
avl_dbase *db; |
| 942 |
PgStat_StatDBEntry *entry; |
| 943 |
|
| 944 |
/* only consider this database if it has a pgstat entry */ |
| 945 |
entry = pgstat_fetch_stat_dbentry(newdb); |
| 946 |
if (entry != NULL) |
| 947 |
{ |
| 948 |
/* we assume it isn't found because the hash was just created */ |
| 949 |
db = hash_search(dbhash, &newdb, HASH_ENTER, NULL); |
| 950 |
|
| 951 |
/* hash_search already filled in the key */ |
| 952 |
db->adl_score = score++; |
| 953 |
/* next_worker is filled in later */ |
| 954 |
} |
| 955 |
} |
| 956 |
|
| 957 |
/* Now insert the databases from the existing list */ |
| 958 |
dlist_foreach(iter, &DatabaseList) |
| 959 |
{ |
| 960 |
avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur); |
| 961 |
avl_dbase *db; |
| 962 |
bool found; |
| 963 |
PgStat_StatDBEntry *entry; |
| 964 |
|
| 965 |
/* |
| 966 |
* skip databases with no stat entries -- in particular, this gets rid |
| 967 |
* of dropped databases |
| 968 |
*/ |
| 969 |
entry = pgstat_fetch_stat_dbentry(avdb->adl_datid); |
| 970 |
if (entry == NULL) |
| 971 |
continue; |
| 972 |
|
| 973 |
db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found); |
| 974 |
|
| 975 |
if (!found) |
| 976 |
{ |
| 977 |
/* hash_search already filled in the key */ |
| 978 |
db->adl_score = score++; |
| 979 |
/* next_worker is filled in later */ |
| 980 |
} |
| 981 |
} |
| 982 |
|
| 983 |
/* finally, insert all qualifying databases not previously inserted */ |
| 984 |
dblist = get_database_list(); |
| 985 |
foreach(cell, dblist) |
| 986 |
{ |
| 987 |
avw_dbase *avdb = lfirst(cell); |
| 988 |
avl_dbase *db; |
| 989 |
bool found; |
| 990 |
PgStat_StatDBEntry *entry; |
| 991 |
|
| 992 |
/* only consider databases with a pgstat entry */ |
| 993 |
entry = pgstat_fetch_stat_dbentry(avdb->adw_datid); |
| 994 |
if (entry == NULL) |
| 995 |
continue; |
| 996 |
|
| 997 |
db = hash_search(dbhash, &(avdb->adw_datid), HASH_ENTER, &found); |
| 998 |
/* only update the score if the database was not already on the hash */ |
| 999 |
if (!found) |
| 1000 |
{ |
| 1001 |
/* hash_search already filled in the key */ |
| 1002 |
db->adl_score = score++; |
| 1003 |
/* next_worker is filled in later */ |
| 1004 |
} |
| 1005 |
} |
| 1006 |
nelems = score; |
| 1007 |
|
| 1008 |
/* from here on, the allocated memory belongs to the new list */ |
| 1009 |
MemoryContextSwitchTo(newcxt); |
| 1010 |
dlist_init(&DatabaseList); |
| 1011 |
|
| 1012 |
if (nelems > 0) |
| 1013 |
{ |
| 1014 |
TimestampTz current_time; |
| 1015 |
int millis_increment; |
| 1016 |
avl_dbase *dbary; |
| 1017 |
avl_dbase *db; |
| 1018 |
HASH_SEQ_STATUS seq; |
| 1019 |
int i; |
| 1020 |
|
| 1021 |
/* put all the hash elements into an array */ |
| 1022 |
dbary = palloc(nelems * sizeof(avl_dbase)); |
| 1023 |
|
| 1024 |
i = 0; |
| 1025 |
hash_seq_init(&seq, dbhash); |
| 1026 |
while ((db = hash_seq_search(&seq)) != NULL) |
| 1027 |
memcpy(&(dbary[i++]), db, sizeof(avl_dbase)); |
| 1028 |
|
| 1029 |
/* sort the array */ |
| 1030 |
qsort(dbary, nelems, sizeof(avl_dbase), db_comparator); |
| 1031 |
|
| 1032 |
/* |
| 1033 |
* Determine the time interval between databases in the schedule. If |
| 1034 |
* we see that the configured naptime would take us to sleep times |
| 1035 |
* lower than our min sleep time (which launcher_determine_sleep is |
| 1036 |
* coded not to allow), silently use a larger naptime (but don't touch |
| 1037 |
* the GUC variable). |
| 1038 |
*/ |
| 1039 |
millis_increment = 1000.0 * autovacuum_naptime / nelems; |
| 1040 |
if (millis_increment <= MIN_AUTOVAC_SLEEPTIME) |
| 1041 |
millis_increment = MIN_AUTOVAC_SLEEPTIME * 1.1; |
| 1042 |
|
| 1043 |
current_time = GetCurrentTimestamp(); |
| 1044 |
|
| 1045 |
/* |
| 1046 |
* move the elements from the array into the dlist, setting the |
| 1047 |
* next_worker while walking the array |
| 1048 |
*/ |
| 1049 |
for (i = 0; i < nelems; i++) |
| 1050 |
{ |
| 1051 |
db = &(dbary[i]); |
| 1052 |
|
| 1053 |
current_time = TimestampTzPlusMilliseconds(current_time, |
| 1054 |
millis_increment); |
| 1055 |
db->adl_next_worker = current_time; |
| 1056 |
|
| 1057 |
/* later elements should go closer to the head of the list */ |
| 1058 |
dlist_push_head(&DatabaseList, &db->adl_node); |
| 1059 |
} |
| 1060 |
} |
| 1061 |
|
| 1062 |
/* all done, clean up memory */ |
| 1063 |
if (DatabaseListCxt != NULL) |
| 1064 |
MemoryContextDelete(DatabaseListCxt); |
| 1065 |
MemoryContextDelete(tmpcxt); |
| 1066 |
DatabaseListCxt = newcxt; |
| 1067 |
MemoryContextSwitchTo(oldcxt); |
| 1068 |
} |
| 1069 |
|
| 1070 |
/* qsort comparator for avl_dbase, using adl_score */ |
| 1071 |
static int |
| 1072 |
db_comparator(const void *a, const void *b) |
| 1073 |
{ |
| 1074 |
return pg_cmp_s32(((const avl_dbase *) b)->adl_score, |
| 1075 |
((const avl_dbase *) a)->adl_score); |
| 1076 |
} |
| 1077 |
|
| 1078 |
/* |
| 1079 |
* do_start_worker |
| 1080 |
* |
| 1081 |
* Bare-bones procedure for starting an autovacuum worker from the launcher. |
| 1082 |
* It determines what database to work on, sets up shared memory stuff and |
| 1083 |
* signals postmaster to start the worker. It fails gracefully if invoked when |
| 1084 |
* autovacuum_workers are already active. |
| 1085 |
* |
| 1086 |
* Return value is the OID of the database that the worker is going to process, |
| 1087 |
* or InvalidOid if no worker was actually started. |
| 1088 |
*/ |
| 1089 |
static Oid |
| 1090 |
do_start_worker(void) |
| 1091 |
{ |
| 1092 |
List *dblist; |
| 1093 |
ListCell *cell; |
| 1094 |
TransactionId xidForceLimit; |
| 1095 |
MultiXactId multiForceLimit; |
| 1096 |
bool for_xid_wrap; |
| 1097 |
bool for_multi_wrap; |
| 1098 |
avw_dbase *avdb; |
| 1099 |
TimestampTz current_time; |
| 1100 |
bool skipit = false; |
| 1101 |
Oid retval = InvalidOid; |
| 1102 |
MemoryContext tmpcxt, |
| 1103 |
oldcxt; |
| 1104 |
|
| 1105 |
/* return quickly when there are no free workers */ |
| 1106 |
LWLockAcquire(AutovacuumLock, LW_SHARED); |
| 1107 |
if (!av_worker_available()) |
| 1108 |
{ |
| 1109 |
LWLockRelease(AutovacuumLock); |
| 1110 |
return InvalidOid; |
| 1111 |
} |
| 1112 |
LWLockRelease(AutovacuumLock); |
| 1113 |
|
| 1114 |
/* |
| 1115 |
* Create and switch to a temporary context to avoid leaking the memory |
| 1116 |
* allocated for the database list. |
| 1117 |
*/ |
| 1118 |
tmpcxt = AllocSetContextCreate(CurrentMemoryContext, |
| 1119 |
"Autovacuum start worker (tmp)", |
| 1120 |
ALLOCSET_DEFAULT_SIZES); |
| 1121 |
oldcxt = MemoryContextSwitchTo(tmpcxt); |
| 1122 |
|
| 1123 |
/* Get a list of databases */ |
| 1124 |
dblist = get_database_list(); |
| 1125 |
|
| 1126 |
/* |
| 1127 |
* Determine the oldest datfrozenxid/relfrozenxid that we will allow to |
| 1128 |
* pass without forcing a vacuum. (This limit can be tightened for |
| 1129 |
* particular tables, but not loosened.) |
| 1130 |
*/ |
| 1131 |
recentXid = ReadNextTransactionId(); |
| 1132 |
xidForceLimit = recentXid - autovacuum_freeze_max_age; |
| 1133 |
/* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */ |
| 1134 |
/* this can cause the limit to go backwards by 3, but that's OK */ |
| 1135 |
if (xidForceLimit < FirstNormalTransactionId) |
| 1136 |
xidForceLimit -= FirstNormalTransactionId; |
| 1137 |
|
| 1138 |
/* Also determine the oldest datminmxid we will consider. */ |
| 1139 |
recentMulti = ReadNextMultiXactId(); |
| 1140 |
multiForceLimit = recentMulti - MultiXactMemberFreezeThreshold(); |
| 1141 |
if (multiForceLimit < FirstMultiXactId) |
| 1142 |
multiForceLimit -= FirstMultiXactId; |
| 1143 |
|
| 1144 |
/* |
| 1145 |
* Choose a database to connect to. We pick the database that was least |
| 1146 |
* recently auto-vacuumed, or one that needs vacuuming to prevent Xid |
| 1147 |
* wraparound-related data loss. If any db at risk of Xid wraparound is |
| 1148 |
* found, we pick the one with oldest datfrozenxid, independently of |
| 1149 |
* autovacuum times; similarly we pick the one with the oldest datminmxid |
| 1150 |
* if any is in MultiXactId wraparound. Note that those in Xid wraparound |
| 1151 |
* danger are given more priority than those in multi wraparound danger. |
| 1152 |
* |
| 1153 |
* Note that a database with no stats entry is not considered, except for |
| 1154 |
* Xid wraparound purposes. The theory is that if no one has ever |
| 1155 |
* connected to it since the stats were last initialized, it doesn't need |
| 1156 |
* vacuuming. |
| 1157 |
* |
| 1158 |
* XXX This could be improved if we had more info about whether it needs |
| 1159 |
* vacuuming before connecting to it. Perhaps look through the pgstats |
| 1160 |
* data for the database's tables? One idea is to keep track of the |
| 1161 |
* number of new and dead tuples per database in pgstats. However it |
| 1162 |
* isn't clear how to construct a metric that measures that and not cause |
| 1163 |
* starvation for less busy databases. |
| 1164 |
*/ |
| 1165 |
avdb = NULL; |
| 1166 |
for_xid_wrap = false; |
| 1167 |
for_multi_wrap = false; |
| 1168 |
current_time = GetCurrentTimestamp(); |
| 1169 |
foreach(cell, dblist) |
| 1170 |
{ |
| 1171 |
avw_dbase *tmp = lfirst(cell); |
| 1172 |
dlist_iter iter; |
| 1173 |
|
| 1174 |
/* Check to see if this one is at risk of wraparound */ |
| 1175 |
if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit)) |
| 1176 |
{ |
| 1177 |
if (avdb == NULL || |
| 1178 |
TransactionIdPrecedes(tmp->adw_frozenxid, |
| 1179 |
avdb->adw_frozenxid)) |
| 1180 |
avdb = tmp; |
| 1181 |
for_xid_wrap = true; |
| 1182 |
continue; |
| 1183 |
} |
| 1184 |
else if (for_xid_wrap) |
| 1185 |
continue; /* ignore not-at-risk DBs */ |
| 1186 |
else if (MultiXactIdPrecedes(tmp->adw_minmulti, multiForceLimit)) |
| 1187 |
{ |
| 1188 |
if (avdb == NULL || |
| 1189 |
MultiXactIdPrecedes(tmp->adw_minmulti, avdb->adw_minmulti)) |
| 1190 |
avdb = tmp; |
| 1191 |
for_multi_wrap = true; |
| 1192 |
continue; |
| 1193 |
} |
| 1194 |
else if (for_multi_wrap) |
| 1195 |
continue; /* ignore not-at-risk DBs */ |
| 1196 |
|
| 1197 |
/* Find pgstat entry if any */ |
| 1198 |
tmp->adw_entry = pgstat_fetch_stat_dbentry(tmp->adw_datid); |
| 1199 |
|
| 1200 |
/* |
| 1201 |
* Skip a database with no pgstat entry; it means it hasn't seen any |
| 1202 |
* activity. |
| 1203 |
*/ |
| 1204 |
if (!tmp->adw_entry) |
| 1205 |
continue; |
| 1206 |
|
| 1207 |
/* |
| 1208 |
* Also, skip a database that appears on the database list as having |
| 1209 |
* been processed recently (less than autovacuum_naptime seconds ago). |
| 1210 |
* We do this so that we don't select a database which we just |
| 1211 |
* selected, but that pgstat hasn't gotten around to updating the last |
| 1212 |
* autovacuum time yet. |
| 1213 |
*/ |
| 1214 |
skipit = false; |
| 1215 |
|
| 1216 |
dlist_reverse_foreach(iter, &DatabaseList) |
| 1217 |
{ |
| 1218 |
avl_dbase *dbp = dlist_container(avl_dbase, adl_node, iter.cur); |
| 1219 |
|
| 1220 |
if (dbp->adl_datid == tmp->adw_datid) |
| 1221 |
{ |
| 1222 |
/* |
| 1223 |
* Skip this database if its next_worker value falls between |
| 1224 |
* the current time and the current time plus naptime. |
| 1225 |
*/ |
| 1226 |
if (!TimestampDifferenceExceeds(dbp->adl_next_worker, |
| 1227 |
current_time, 0) && |
| 1228 |
!TimestampDifferenceExceeds(current_time, |
| 1229 |
dbp->adl_next_worker, |
| 1230 |
autovacuum_naptime * 1000)) |
| 1231 |
skipit = true; |
| 1232 |
|
| 1233 |
break; |
| 1234 |
} |
| 1235 |
} |
| 1236 |
if (skipit) |
| 1237 |
continue; |
| 1238 |
|
| 1239 |
/* |
| 1240 |
* Remember the db with oldest autovac time. (If we are here, both |
| 1241 |
* tmp->entry and db->entry must be non-null.) |
| 1242 |
*/ |
| 1243 |
if (avdb == NULL || |
| 1244 |
tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time) |
| 1245 |
avdb = tmp; |
| 1246 |
} |
| 1247 |
|
| 1248 |
/* Found a database -- process it */ |
| 1249 |
if (avdb != NULL) |
| 1250 |
{ |
| 1251 |
WorkerInfo worker; |
| 1252 |
dlist_node *wptr; |
| 1253 |
|
| 1254 |
LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); |
| 1255 |
|
| 1256 |
/* |
| 1257 |
* Get a worker entry from the freelist. We checked above, so there |
| 1258 |
* really should be a free slot. |
| 1259 |
*/ |
| 1260 |
wptr = dclist_pop_head_node(&AutoVacuumShmem->av_freeWorkers); |
| 1261 |
|
| 1262 |
worker = dlist_container(WorkerInfoData, wi_links, wptr); |
| 1263 |
worker->wi_dboid = avdb->adw_datid; |
| 1264 |
worker->wi_proc = NULL; |
| 1265 |
worker->wi_launchtime = GetCurrentTimestamp(); |
| 1266 |
|
| 1267 |
AutoVacuumShmem->av_startingWorker = worker; |
| 1268 |
|
| 1269 |
LWLockRelease(AutovacuumLock); |
| 1270 |
|
| 1271 |
SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER); |
| 1272 |
|
| 1273 |
retval = avdb->adw_datid; |
| 1274 |
} |
| 1275 |
else if (skipit) |
| 1276 |
{ |
| 1277 |
/* |
| 1278 |
* If we skipped all databases on the list, rebuild it, because it |
| 1279 |
* probably contains a dropped database. |
| 1280 |
*/ |
| 1281 |
rebuild_database_list(InvalidOid); |
| 1282 |
} |
| 1283 |
|
| 1284 |
MemoryContextSwitchTo(oldcxt); |
| 1285 |
MemoryContextDelete(tmpcxt); |
| 1286 |
|
| 1287 |
return retval; |
| 1288 |
} |
| 1289 |
|
| 1290 |
/* |
| 1291 |
* launch_worker |
| 1292 |
* |
| 1293 |
* Wrapper for starting a worker from the launcher. Besides actually starting |
| 1294 |
* it, update the database list to reflect the next time that another one will |
| 1295 |
* need to be started on the selected database. The actual database choice is |
| 1296 |
* left to do_start_worker. |
| 1297 |
* |
| 1298 |
* This routine is also expected to insert an entry into the database list if |
| 1299 |
* the selected database was previously absent from the list. |
| 1300 |
*/ |
| 1301 |
static void |
| 1302 |
launch_worker(TimestampTz now) |
| 1303 |
{ |
| 1304 |
Oid dbid; |
| 1305 |
dlist_iter iter; |
| 1306 |
|
| 1307 |
dbid = do_start_worker(); |
| 1308 |
if (OidIsValid(dbid)) |
| 1309 |
{ |
| 1310 |
bool found = false; |
| 1311 |
|
| 1312 |
/* |
| 1313 |
* Walk the database list and update the corresponding entry. If the |
| 1314 |
* database is not on the list, we'll recreate the list. |
| 1315 |
*/ |
| 1316 |
dlist_foreach(iter, &DatabaseList) |
| 1317 |
{ |
| 1318 |
avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur); |
| 1319 |
|
| 1320 |
if (avdb->adl_datid == dbid) |
| 1321 |
{ |
| 1322 |
found = true; |
| 1323 |
|
| 1324 |
/* |
| 1325 |
* add autovacuum_naptime seconds to the current time, and use |
| 1326 |
* that as the new "next_worker" field for this database. |
| 1327 |
*/ |
| 1328 |
avdb->adl_next_worker = |
| 1329 |
TimestampTzPlusMilliseconds(now, autovacuum_naptime * 1000); |
| 1330 |
|
| 1331 |
dlist_move_head(&DatabaseList, iter.cur); |
| 1332 |
break; |
| 1333 |
} |
| 1334 |
} |
| 1335 |
|
| 1336 |
/* |
| 1337 |
* If the database was not present in the database list, we rebuild |
| 1338 |
* the list. It's possible that the database does not get into the |
| 1339 |
* list anyway, for example if it's a database that doesn't have a |
| 1340 |
* pgstat entry, but this is not a problem because we don't want to |
| 1341 |
* schedule workers regularly into those in any case. |
| 1342 |
*/ |
| 1343 |
if (!found) |
| 1344 |
rebuild_database_list(dbid); |
| 1345 |
} |
| 1346 |
} |
| 1347 |
|
| 1348 |
/* |
| 1349 |
* Called from postmaster to signal a failure to fork a process to become |
| 1350 |
* worker. The postmaster should kill(SIGUSR2) the launcher shortly |
| 1351 |
* after calling this function. |
| 1352 |
*/ |
| 1353 |
void |
| 1354 |
AutoVacWorkerFailed(void) |
| 1355 |
{ |
| 1356 |
AutoVacuumShmem->av_signal[AutoVacForkFailed] = true; |
| 1357 |
} |
| 1358 |
|
| 1359 |
/* SIGUSR2: a worker is up and running, or just finished, or failed to fork */ |
| 1360 |
static void |
| 1361 |
avl_sigusr2_handler(SIGNAL_ARGS) |
| 1362 |
{ |
| 1363 |
got_SIGUSR2 = true; |
| 1364 |
SetLatch(MyLatch); |
| 1365 |
} |
| 1366 |
|
| 1367 |
|
| 1368 |
/******************************************************************** |
| 1369 |
* AUTOVACUUM WORKER CODE |
| 1370 |
********************************************************************/ |
| 1371 |
|
| 1372 |
/* |
| 1373 |
* Main entry point for autovacuum worker processes. |
| 1374 |
*/ |
| 1375 |
void |
| 1376 |
AutoVacWorkerMain(const void *startup_data, size_t startup_data_len) |
| 1377 |
{ |
| 1378 |
sigjmp_buf local_sigjmp_buf; |
| 1379 |
Oid dbid; |
| 1380 |
|
| 1381 |
Assert(startup_data_len == 0); |
| 1382 |
|
| 1383 |
/* Release postmaster's working memory context */ |
| 1384 |
if (PostmasterContext) |
| 1385 |
{ |
| 1386 |
MemoryContextDelete(PostmasterContext); |
| 1387 |
PostmasterContext = NULL; |
| 1388 |
} |
| 1389 |
|
| 1390 |
MyBackendType = B_AUTOVAC_WORKER; |
| 1391 |
init_ps_display(NULL); |
| 1392 |
|
| 1393 |
Assert(GetProcessingMode() == InitProcessing); |
| 1394 |
|
| 1395 |
/* |
| 1396 |
* Set up signal handlers. We operate on databases much like a regular |
| 1397 |
* backend, so we use the same signal handling. See equivalent code in |
| 1398 |
* tcop/postgres.c. |
| 1399 |
*/ |
| 1400 |
pqsignal(SIGHUP, SignalHandlerForConfigReload); |
| 1401 |
|
| 1402 |
/* |
| 1403 |
* SIGINT is used to signal canceling the current table's vacuum; SIGTERM |
| 1404 |
* means abort and exit cleanly, and SIGQUIT means abandon ship. |
| 1405 |
*/ |
| 1406 |
pqsignal(SIGINT, StatementCancelHandler); |
| 1407 |
pqsignal(SIGTERM, die); |
| 1408 |
/* SIGQUIT handler was already set up by InitPostmasterChild */ |
| 1409 |
|
| 1410 |
InitializeTimeouts(); /* establishes SIGALRM handler */ |
| 1411 |
|
| 1412 |
pqsignal(SIGPIPE, SIG_IGN); |
| 1413 |
pqsignal(SIGUSR1, procsignal_sigusr1_handler); |
| 1414 |
pqsignal(SIGUSR2, SIG_IGN); |
| 1415 |
pqsignal(SIGFPE, FloatExceptionHandler); |
| 1416 |
pqsignal(SIGCHLD, SIG_DFL); |
| 1417 |
|
| 1418 |
/* |
| 1419 |
* Create a per-backend PGPROC struct in shared memory. We must do this |
| 1420 |
* before we can use LWLocks or access any shared memory. |
| 1421 |
*/ |
| 1422 |
InitProcess(); |
| 1423 |
|
| 1424 |
/* Early initialization */ |
| 1425 |
BaseInit(); |
| 1426 |
|
| 1427 |
/* |
| 1428 |
* If an exception is encountered, processing resumes here. |
| 1429 |
* |
| 1430 |
* Unlike most auxiliary processes, we don't attempt to continue |
| 1431 |
* processing after an error; we just clean up and exit. The autovac |
| 1432 |
* launcher is responsible for spawning another worker later. |
| 1433 |
* |
| 1434 |
* Note that we use sigsetjmp(..., 1), so that the prevailing signal mask |
| 1435 |
* (to wit, BlockSig) will be restored when longjmp'ing to here. Thus, |
| 1436 |
* signals other than SIGQUIT will be blocked until we exit. It might |
| 1437 |
* seem that this policy makes the HOLD_INTERRUPTS() call redundant, but |
| 1438 |
* it is not since InterruptPending might be set already. |
| 1439 |
*/ |
| 1440 |
if (sigsetjmp(local_sigjmp_buf, 1) != 0) |
| 1441 |
{ |
| 1442 |
/* since not using PG_TRY, must reset error stack by hand */ |
| 1443 |
error_context_stack = NULL; |
| 1444 |
|
| 1445 |
/* Prevents interrupts while cleaning up */ |
| 1446 |
HOLD_INTERRUPTS(); |
| 1447 |
|
| 1448 |
/* Report the error to the server log */ |
| 1449 |
EmitErrorReport(); |
| 1450 |
|
| 1451 |
/* |
| 1452 |
* We can now go away. Note that because we called InitProcess, a |
| 1453 |
* callback was registered to do ProcKill, which will clean up |
| 1454 |
* necessary state. |
| 1455 |
*/ |
| 1456 |
proc_exit(0); |
| 1457 |
} |
| 1458 |
|
| 1459 |
/* We can now handle ereport(ERROR) */ |
| 1460 |
PG_exception_stack = &local_sigjmp_buf; |
| 1461 |
|
| 1462 |
sigprocmask(SIG_SETMASK, &UnBlockSig, NULL); |
| 1463 |
|
| 1464 |
/* |
| 1465 |
* Set always-secure search path, so malicious users can't redirect user |
| 1466 |
* code (e.g. pg_index.indexprs). (That code runs in a |
| 1467 |
* SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not |
| 1468 |
* take control of the entire autovacuum worker in any case.) |
| 1469 |
*/ |
| 1470 |
SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE); |
| 1471 |
|
| 1472 |
/* |
| 1473 |
* Force zero_damaged_pages OFF in the autovac process, even if it is set |
| 1474 |
* in postgresql.conf. We don't really want such a dangerous option being |
| 1475 |
* applied non-interactively. |
| 1476 |
*/ |
| 1477 |
SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE); |
| 1478 |
|
| 1479 |
/* |
| 1480 |
* Force settable timeouts off to avoid letting these settings prevent |
| 1481 |
* regular maintenance from being executed. |
| 1482 |
*/ |
| 1483 |
SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE); |
| 1484 |
SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE); |
| 1485 |
SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE); |
| 1486 |
SetConfigOption("idle_in_transaction_session_timeout", "0", |
| 1487 |
PGC_SUSET, PGC_S_OVERRIDE); |
| 1488 |
|
| 1489 |
/* |
| 1490 |
* Force default_transaction_isolation to READ COMMITTED. We don't want |
| 1491 |
* to pay the overhead of serializable mode, nor add any risk of causing |
| 1492 |
* deadlocks or delaying other transactions. |
| 1493 |
*/ |
| 1494 |
SetConfigOption("default_transaction_isolation", "read committed", |
| 1495 |
PGC_SUSET, PGC_S_OVERRIDE); |
| 1496 |
|
| 1497 |
/* |
| 1498 |
* Force synchronous replication off to allow regular maintenance even if |
| 1499 |
* we are waiting for standbys to connect. This is important to ensure we |
| 1500 |
* aren't blocked from performing anti-wraparound tasks. |
| 1501 |
*/ |
| 1502 |
if (synchronous_commit > SYNCHRONOUS_COMMIT_LOCAL_FLUSH) |
| 1503 |
SetConfigOption("synchronous_commit", "local", |
| 1504 |
PGC_SUSET, PGC_S_OVERRIDE); |
| 1505 |
|
| 1506 |
/* |
| 1507 |
* Even when system is configured to use a different fetch consistency, |
| 1508 |
* for autovac we always want fresh stats. |
| 1509 |
*/ |
| 1510 |
SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE); |
| 1511 |
|
| 1512 |
/* |
| 1513 |
* Get the info about the database we're going to work on. |
| 1514 |
*/ |
| 1515 |
LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); |
| 1516 |
|
| 1517 |
/* |
| 1518 |
* beware of startingWorker being INVALID; this should normally not |
| 1519 |
* happen, but if a worker fails after forking and before this, the |
| 1520 |
* launcher might have decided to remove it from the queue and start |
| 1521 |
* again. |
| 1522 |
*/ |
| 1523 |
if (AutoVacuumShmem->av_startingWorker != NULL) |
| 1524 |
{ |
| 1525 |
MyWorkerInfo = AutoVacuumShmem->av_startingWorker; |
| 1526 |
dbid = MyWorkerInfo->wi_dboid; |
| 1527 |
MyWorkerInfo->wi_proc = MyProc; |
| 1528 |
|
| 1529 |
/* insert into the running list */ |
| 1530 |
dlist_push_head(&AutoVacuumShmem->av_runningWorkers, |
| 1531 |
&MyWorkerInfo->wi_links); |
| 1532 |
|
| 1533 |
/* |
| 1534 |
* remove from the "starting" pointer, so that the launcher can start |
| 1535 |
* a new worker if required |
| 1536 |
*/ |
| 1537 |
AutoVacuumShmem->av_startingWorker = NULL; |
| 1538 |
LWLockRelease(AutovacuumLock); |
| 1539 |
|
| 1540 |
on_shmem_exit(FreeWorkerInfo, 0); |
| 1541 |
|
| 1542 |
/* wake up the launcher */ |
| 1543 |
if (AutoVacuumShmem->av_launcherpid != 0) |
| 1544 |
kill(AutoVacuumShmem->av_launcherpid, SIGUSR2); |
| 1545 |
} |
| 1546 |
else |
| 1547 |
{ |
| 1548 |
/* no worker entry for me, go away */ |
| 1549 |
elog(WARNING, "autovacuum worker started without a worker entry"); |
| 1550 |
dbid = InvalidOid; |
| 1551 |
LWLockRelease(AutovacuumLock); |
| 1552 |
} |
| 1553 |
|
| 1554 |
if (OidIsValid(dbid)) |
| 1555 |
{ |
| 1556 |
char dbname[NAMEDATALEN]; |
| 1557 |
|
| 1558 |
/* |
| 1559 |
* Report autovac startup to the cumulative stats system. We |
| 1560 |
* deliberately do this before InitPostgres, so that the |
| 1561 |
* last_autovac_time will get updated even if the connection attempt |
| 1562 |
* fails. This is to prevent autovac from getting "stuck" repeatedly |
| 1563 |
* selecting an unopenable database, rather than making any progress |
| 1564 |
* on stuff it can connect to. |
| 1565 |
*/ |
| 1566 |
pgstat_report_autovac(dbid); |
| 1567 |
|
| 1568 |
/* |
| 1569 |
* Connect to the selected database, specifying no particular user, |
| 1570 |
* and ignoring datallowconn. Collect the database's name for |
| 1571 |
* display. |
| 1572 |
* |
| 1573 |
* Note: if we have selected a just-deleted database (due to using |
| 1574 |
* stale stats info), we'll fail and exit here. |
| 1575 |
*/ |
| 1576 |
InitPostgres(NULL, dbid, NULL, InvalidOid, |
| 1577 |
INIT_PG_OVERRIDE_ALLOW_CONNS, |
| 1578 |
dbname); |
| 1579 |
SetProcessingMode(NormalProcessing); |
| 1580 |
set_ps_display(dbname); |
| 1581 |
ereport(DEBUG1, |
| 1582 |
(errmsg_internal("autovacuum: processing database \"%s\"", dbname))); |
| 1583 |
|
| 1584 |
if (PostAuthDelay) |
| 1585 |
pg_usleep(PostAuthDelay * 1000000L); |
| 1586 |
|
| 1587 |
/* And do an appropriate amount of work */ |
| 1588 |
recentXid = ReadNextTransactionId(); |
| 1589 |
recentMulti = ReadNextMultiXactId(); |
| 1590 |
do_autovacuum(); |
| 1591 |
} |
| 1592 |
|
| 1593 |
/* |
| 1594 |
* The launcher will be notified of my death in ProcKill, *if* we managed |
| 1595 |
* to get a worker slot at all |
| 1596 |
*/ |
| 1597 |
|
| 1598 |
/* All done, go away */ |
| 1599 |
proc_exit(0); |
| 1600 |
} |
| 1601 |
|
| 1602 |
/* |
| 1603 |
* Return a WorkerInfo to the free list |
| 1604 |
*/ |
| 1605 |
static void |
| 1606 |
FreeWorkerInfo(int code, Datum arg) |
| 1607 |
{ |
| 1608 |
if (MyWorkerInfo != NULL) |
| 1609 |
{ |
| 1610 |
LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); |
| 1611 |
|
| 1612 |
/* |
| 1613 |
* Wake the launcher up so that he can launch a new worker immediately |
| 1614 |
* if required. We only save the launcher's PID in local memory here; |
| 1615 |
* the actual signal will be sent when the PGPROC is recycled. Note |
| 1616 |
* that we always do this, so that the launcher can rebalance the cost |
| 1617 |
* limit setting of the remaining workers. |
| 1618 |
* |
| 1619 |
* We somewhat ignore the risk that the launcher changes its PID |
| 1620 |
* between us reading it and the actual kill; we expect ProcKill to be |
| 1621 |
* called shortly after us, and we assume that PIDs are not reused too |
| 1622 |
* quickly after a process exits. |
| 1623 |
*/ |
| 1624 |
AutovacuumLauncherPid = AutoVacuumShmem->av_launcherpid; |
| 1625 |
|
| 1626 |
dlist_delete(&MyWorkerInfo->wi_links); |
| 1627 |
MyWorkerInfo->wi_dboid = InvalidOid; |
| 1628 |
MyWorkerInfo->wi_tableoid = InvalidOid; |
| 1629 |
MyWorkerInfo->wi_sharedrel = false; |
| 1630 |
MyWorkerInfo->wi_proc = NULL; |
| 1631 |
MyWorkerInfo->wi_launchtime = 0; |
| 1632 |
pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance); |
| 1633 |
dclist_push_head(&AutoVacuumShmem->av_freeWorkers, |
| 1634 |
&MyWorkerInfo->wi_links); |
| 1635 |
/* not mine anymore */ |
| 1636 |
MyWorkerInfo = NULL; |
| 1637 |
|
| 1638 |
/* |
| 1639 |
* now that we're inactive, cause a rebalancing of the surviving |
| 1640 |
* workers |
| 1641 |
*/ |
| 1642 |
AutoVacuumShmem->av_signal[AutoVacRebalance] = true; |
| 1643 |
LWLockRelease(AutovacuumLock); |
| 1644 |
} |
| 1645 |
} |
| 1646 |
|
| 1647 |
/* |
| 1648 |
* Update vacuum cost-based delay-related parameters for autovacuum workers and |
| 1649 |
* backends executing VACUUM or ANALYZE using the value of relevant GUCs and |
| 1650 |
* global state. This must be called during setup for vacuum and after every |
| 1651 |
* config reload to ensure up-to-date values. |
| 1652 |
*/ |
| 1653 |
void |
| 1654 |
VacuumUpdateCosts(void) |
| 1655 |
{ |
| 1656 |
if (MyWorkerInfo) |
| 1657 |
{ |
| 1658 |
if (av_storage_param_cost_delay >= 0) |
| 1659 |
vacuum_cost_delay = av_storage_param_cost_delay; |
| 1660 |
else if (autovacuum_vac_cost_delay >= 0) |
| 1661 |
vacuum_cost_delay = autovacuum_vac_cost_delay; |
| 1662 |
else |
| 1663 |
/* fall back to VacuumCostDelay */ |
| 1664 |
vacuum_cost_delay = VacuumCostDelay; |
| 1665 |
|
| 1666 |
AutoVacuumUpdateCostLimit(); |
| 1667 |
} |
| 1668 |
else |
| 1669 |
{ |
| 1670 |
/* Must be explicit VACUUM or ANALYZE */ |
| 1671 |
vacuum_cost_delay = VacuumCostDelay; |
| 1672 |
vacuum_cost_limit = VacuumCostLimit; |
| 1673 |
} |
| 1674 |
|
| 1675 |
/* |
| 1676 |
* If configuration changes are allowed to impact VacuumCostActive, make |
| 1677 |
* sure it is updated. |
| 1678 |
*/ |
| 1679 |
if (VacuumFailsafeActive) |
| 1680 |
Assert(!VacuumCostActive); |
| 1681 |
else if (vacuum_cost_delay > 0) |
| 1682 |
VacuumCostActive = true; |
| 1683 |
else |
| 1684 |
{ |
| 1685 |
VacuumCostActive = false; |
| 1686 |
VacuumCostBalance = 0; |
| 1687 |
} |
| 1688 |
|
| 1689 |
/* |
| 1690 |
* Since the cost logging requires a lock, avoid rendering the log message |
| 1691 |
* in case we are using a message level where the log wouldn't be emitted. |
| 1692 |
*/ |
| 1693 |
if (MyWorkerInfo && message_level_is_interesting(DEBUG2)) |
| 1694 |
{ |
| 1695 |
Oid dboid, |
| 1696 |
tableoid; |
| 1697 |
|
| 1698 |
Assert(!LWLockHeldByMe(AutovacuumLock)); |
| 1699 |
|
| 1700 |
LWLockAcquire(AutovacuumLock, LW_SHARED); |
| 1701 |
dboid = MyWorkerInfo->wi_dboid; |
| 1702 |
tableoid = MyWorkerInfo->wi_tableoid; |
| 1703 |
LWLockRelease(AutovacuumLock); |
| 1704 |
|
| 1705 |
elog(DEBUG2, |
| 1706 |
"Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)", |
| 1707 |
dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes", |
| 1708 |
vacuum_cost_limit, vacuum_cost_delay, |
| 1709 |
vacuum_cost_delay > 0 ? "yes" : "no", |
| 1710 |
VacuumFailsafeActive ? "yes" : "no"); |
| 1711 |
} |
| 1712 |
} |
| 1713 |
|
| 1714 |
/* |
| 1715 |
* Update vacuum_cost_limit with the correct value for an autovacuum worker, |
| 1716 |
* given the value of other relevant cost limit parameters and the number of |
| 1717 |
* workers across which the limit must be balanced. Autovacuum workers must |
| 1718 |
* call this regularly in case av_nworkersForBalance has been updated by |
| 1719 |
* another worker or by the autovacuum launcher. They must also call it after a |
| 1720 |
* config reload. |
| 1721 |
*/ |
| 1722 |
void |
| 1723 |
AutoVacuumUpdateCostLimit(void) |
| 1724 |
{ |
| 1725 |
if (!MyWorkerInfo) |
| 1726 |
return; |
| 1727 |
|
| 1728 |
/* |
| 1729 |
* note: in cost_limit, zero also means use value from elsewhere, because |
| 1730 |
* zero is not a valid value. |
| 1731 |
*/ |
| 1732 |
|
| 1733 |
if (av_storage_param_cost_limit > 0) |
| 1734 |
vacuum_cost_limit = av_storage_param_cost_limit; |
| 1735 |
else |
| 1736 |
{ |
| 1737 |
int nworkers_for_balance; |
| 1738 |
|
| 1739 |
if (autovacuum_vac_cost_limit > 0) |
| 1740 |
vacuum_cost_limit = autovacuum_vac_cost_limit; |
| 1741 |
else |
| 1742 |
vacuum_cost_limit = VacuumCostLimit; |
| 1743 |
|
| 1744 |
/* Only balance limit if no cost-related storage parameters specified */ |
| 1745 |
if (pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance)) |
| 1746 |
return; |
| 1747 |
|
| 1748 |
Assert(vacuum_cost_limit > 0); |
| 1749 |
|
| 1750 |
nworkers_for_balance = pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance); |
| 1751 |
|
| 1752 |
/* There is at least 1 autovac worker (this worker) */ |
| 1753 |
if (nworkers_for_balance <= 0) |
| 1754 |
elog(ERROR, "nworkers_for_balance must be > 0"); |
| 1755 |
|
| 1756 |
vacuum_cost_limit = Max(vacuum_cost_limit / nworkers_for_balance, 1); |
| 1757 |
} |
| 1758 |
} |
| 1759 |
|
| 1760 |
/* |
| 1761 |
* autovac_recalculate_workers_for_balance |
| 1762 |
* Recalculate the number of workers to consider, given cost-related |
| 1763 |
* storage parameters and the current number of active workers. |
| 1764 |
* |
| 1765 |
* Caller must hold the AutovacuumLock in at least shared mode to access |
| 1766 |
* worker->wi_proc. |
| 1767 |
*/ |
| 1768 |
static void |
| 1769 |
autovac_recalculate_workers_for_balance(void) |
| 1770 |
{ |
| 1771 |
dlist_iter iter; |
| 1772 |
int orig_nworkers_for_balance; |
| 1773 |
int nworkers_for_balance = 0; |
| 1774 |
|
| 1775 |
Assert(LWLockHeldByMe(AutovacuumLock)); |
| 1776 |
|
| 1777 |
orig_nworkers_for_balance = |
| 1778 |
pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance); |
| 1779 |
|
| 1780 |
dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers) |
| 1781 |
{ |
| 1782 |
WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur); |
| 1783 |
|
| 1784 |
if (worker->wi_proc == NULL || |
| 1785 |
pg_atomic_unlocked_test_flag(&worker->wi_dobalance)) |
| 1786 |
continue; |
| 1787 |
|
| 1788 |
nworkers_for_balance++; |
| 1789 |
} |
| 1790 |
|
| 1791 |
if (nworkers_for_balance != orig_nworkers_for_balance) |
| 1792 |
pg_atomic_write_u32(&AutoVacuumShmem->av_nworkersForBalance, |
| 1793 |
nworkers_for_balance); |
| 1794 |
} |
| 1795 |
|
| 1796 |
/* |
| 1797 |
* get_database_list |
| 1798 |
* Return a list of all databases found in pg_database. |
| 1799 |
* |
| 1800 |
* The list and associated data is allocated in the caller's memory context, |
| 1801 |
* which is in charge of ensuring that it's properly cleaned up afterwards. |
| 1802 |
* |
| 1803 |
* Note: this is the only function in which the autovacuum launcher uses a |
| 1804 |
* transaction. Although we aren't attached to any particular database and |
| 1805 |
* therefore can't access most catalogs, we do have enough infrastructure |
| 1806 |
* to do a seqscan on pg_database. |
| 1807 |
*/ |
| 1808 |
static List * |
| 1809 |
get_database_list(void) |
| 1810 |
{ |
| 1811 |
List *dblist = NIL; |
| 1812 |
Relation rel; |
| 1813 |
TableScanDesc scan; |
| 1814 |
HeapTuple tup; |
| 1815 |
MemoryContext resultcxt; |
| 1816 |
|
| 1817 |
/* This is the context that we will allocate our output data in */ |
| 1818 |
resultcxt = CurrentMemoryContext; |
| 1819 |
|
| 1820 |
/* |
| 1821 |
* Start a transaction so we can access pg_database. |
| 1822 |
*/ |
| 1823 |
StartTransactionCommand(); |
| 1824 |
|
| 1825 |
rel = table_open(DatabaseRelationId, AccessShareLock); |
| 1826 |
scan = table_beginscan_catalog(rel, 0, NULL); |
| 1827 |
|
| 1828 |
while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection))) |
| 1829 |
{ |
| 1830 |
Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup); |
| 1831 |
avw_dbase *avdb; |
| 1832 |
MemoryContext oldcxt; |
| 1833 |
|
| 1834 |
/* |
| 1835 |
* If database has partially been dropped, we can't, nor need to, |
| 1836 |
* vacuum it. |
| 1837 |
*/ |
| 1838 |
if (database_is_invalid_form(pgdatabase)) |
| 1839 |
{ |
| 1840 |
elog(DEBUG2, |
| 1841 |
"autovacuum: skipping invalid database \"%s\"", |
| 1842 |
NameStr(pgdatabase->datname)); |
| 1843 |
continue; |
| 1844 |
} |
| 1845 |
|
| 1846 |
/* |
| 1847 |
* Allocate our results in the caller's context, not the |
| 1848 |
* transaction's. We do this inside the loop, and restore the original |
| 1849 |
* context at the end, so that leaky things like heap_getnext() are |
| 1850 |
* not called in a potentially long-lived context. |
| 1851 |
*/ |
| 1852 |
oldcxt = MemoryContextSwitchTo(resultcxt); |
| 1853 |
|
| 1854 |
avdb = (avw_dbase *) palloc(sizeof(avw_dbase)); |
| 1855 |
|
| 1856 |
avdb->adw_datid = pgdatabase->oid; |
| 1857 |
avdb->adw_name = pstrdup(NameStr(pgdatabase->datname)); |
| 1858 |
avdb->adw_frozenxid = pgdatabase->datfrozenxid; |
| 1859 |
avdb->adw_minmulti = pgdatabase->datminmxid; |
| 1860 |
/* this gets set later: */ |
| 1861 |
avdb->adw_entry = NULL; |
| 1862 |
|
| 1863 |
dblist = lappend(dblist, avdb); |
| 1864 |
MemoryContextSwitchTo(oldcxt); |
| 1865 |
} |
| 1866 |
|
| 1867 |
table_endscan(scan); |
| 1868 |
table_close(rel, AccessShareLock); |
| 1869 |
|
| 1870 |
CommitTransactionCommand(); |
| 1871 |
|
| 1872 |
/* Be sure to restore caller's memory context */ |
| 1873 |
MemoryContextSwitchTo(resultcxt); |
| 1874 |
|
| 1875 |
return dblist; |
| 1876 |
} |
| 1877 |
|
| 1878 |
/* |
| 1879 |
* Process a database table-by-table |
| 1880 |
* |
| 1881 |
* Note that CHECK_FOR_INTERRUPTS is supposed to be used in certain spots in |
| 1882 |
* order not to ignore shutdown commands for too long. |
| 1883 |
*/ |
| 1884 |
static void |
| 1885 |
do_autovacuum(void) |
| 1886 |
{ |
| 1887 |
Relation classRel; |
| 1888 |
HeapTuple tuple; |
| 1889 |
TableScanDesc relScan; |
| 1890 |
Form_pg_database dbForm; |
| 1891 |
List *table_oids = NIL; |
| 1892 |
List *orphan_oids = NIL; |
| 1893 |
HASHCTL ctl; |
| 1894 |
HTAB *table_toast_map; |
| 1895 |
ListCell *volatile cell; |
| 1896 |
BufferAccessStrategy bstrategy; |
| 1897 |
ScanKeyData key; |
| 1898 |
TupleDesc pg_class_desc; |
| 1899 |
int effective_multixact_freeze_max_age; |
| 1900 |
bool did_vacuum = false; |
| 1901 |
bool found_concurrent_worker = false; |
| 1902 |
int i; |
| 1903 |
|
| 1904 |
/* |
| 1905 |
* StartTransactionCommand and CommitTransactionCommand will automatically |
| 1906 |
* switch to other contexts. We need this one to keep the list of |
| 1907 |
* relations to vacuum/analyze across transactions. |
| 1908 |
*/ |
| 1909 |
AutovacMemCxt = AllocSetContextCreate(TopMemoryContext, |
| 1910 |
"Autovacuum worker", |
| 1911 |
ALLOCSET_DEFAULT_SIZES); |
| 1912 |
MemoryContextSwitchTo(AutovacMemCxt); |
| 1913 |
|
| 1914 |
/* Start a transaction so our commands have one to play into. */ |
| 1915 |
StartTransactionCommand(); |
| 1916 |
|
| 1917 |
/* |
| 1918 |
* This injection point is put in a transaction block to work with a wait |
| 1919 |
* that uses a condition variable. |
| 1920 |
*/ |
| 1921 |
INJECTION_POINT("autovacuum-worker-start", NULL); |
| 1922 |
|
| 1923 |
/* |
| 1924 |
* Compute the multixact age for which freezing is urgent. This is |
| 1925 |
* normally autovacuum_multixact_freeze_max_age, but may be less if we are |
| 1926 |
* short of multixact member space. |
| 1927 |
*/ |
| 1928 |
effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold(); |
| 1929 |
|
| 1930 |
/* |
| 1931 |
* Find the pg_database entry and select the default freeze ages. We use |
| 1932 |
* zero in template and nonconnectable databases, else the system-wide |
| 1933 |
* default. |
| 1934 |
*/ |
| 1935 |
tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId)); |
| 1936 |
if (!HeapTupleIsValid(tuple)) |
| 1937 |
elog(ERROR, "cache lookup failed for database %u", MyDatabaseId); |
| 1938 |
dbForm = (Form_pg_database) GETSTRUCT(tuple); |
| 1939 |
|
| 1940 |
if (dbForm->datistemplate || !dbForm->datallowconn) |
| 1941 |
{ |
| 1942 |
default_freeze_min_age = 0; |
| 1943 |
default_freeze_table_age = 0; |
| 1944 |
default_multixact_freeze_min_age = 0; |
| 1945 |
default_multixact_freeze_table_age = 0; |
| 1946 |
} |
| 1947 |
else |
| 1948 |
{ |
| 1949 |
default_freeze_min_age = vacuum_freeze_min_age; |
| 1950 |
default_freeze_table_age = vacuum_freeze_table_age; |
| 1951 |
default_multixact_freeze_min_age = vacuum_multixact_freeze_min_age; |
| 1952 |
default_multixact_freeze_table_age = vacuum_multixact_freeze_table_age; |
| 1953 |
} |
| 1954 |
|
| 1955 |
ReleaseSysCache(tuple); |
| 1956 |
|
| 1957 |
/* StartTransactionCommand changed elsewhere */ |
| 1958 |
MemoryContextSwitchTo(AutovacMemCxt); |
| 1959 |
|
| 1960 |
classRel = table_open(RelationRelationId, AccessShareLock); |
| 1961 |
|
| 1962 |
/* create a copy so we can use it after closing pg_class */ |
| 1963 |
pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel)); |
| 1964 |
|
| 1965 |
/* create hash table for toast <-> main relid mapping */ |
| 1966 |
ctl.keysize = sizeof(Oid); |
| 1967 |
ctl.entrysize = sizeof(av_relation); |
| 1968 |
|
| 1969 |
table_toast_map = hash_create("TOAST to main relid map", |
| 1970 |
100, |
| 1971 |
&ctl, |
| 1972 |
HASH_ELEM | HASH_BLOBS); |
| 1973 |
|
| 1974 |
/* |
| 1975 |
* Scan pg_class to determine which tables to vacuum. |
| 1976 |
* |
| 1977 |
* We do this in two passes: on the first one we collect the list of plain |
| 1978 |
* relations and materialized views, and on the second one we collect |
| 1979 |
* TOAST tables. The reason for doing the second pass is that during it we |
| 1980 |
* want to use the main relation's pg_class.reloptions entry if the TOAST |
| 1981 |
* table does not have any, and we cannot obtain it unless we know |
| 1982 |
* beforehand what's the main table OID. |
| 1983 |
* |
| 1984 |
* We need to check TOAST tables separately because in cases with short, |
| 1985 |
* wide tables there might be proportionally much more activity in the |
| 1986 |
* TOAST table than in its parent. |
| 1987 |
*/ |
| 1988 |
relScan = table_beginscan_catalog(classRel, 0, NULL); |
| 1989 |
|
| 1990 |
/* |
| 1991 |
* On the first pass, we collect main tables to vacuum, and also the main |
| 1992 |
* table relid to TOAST relid mapping. |
| 1993 |
*/ |
| 1994 |
while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL) |
| 1995 |
{ |
| 1996 |
Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple); |
| 1997 |
PgStat_StatTabEntry *tabentry; |
| 1998 |
AutoVacOpts *relopts; |
| 1999 |
Oid relid; |
| 2000 |
bool dovacuum; |
| 2001 |
bool doanalyze; |
| 2002 |
bool wraparound; |
| 2003 |
|
| 2004 |
if (classForm->relkind != RELKIND_RELATION && |
| 2005 |
classForm->relkind != RELKIND_MATVIEW) |
| 2006 |
continue; |
| 2007 |
|
| 2008 |
relid = classForm->oid; |
| 2009 |
|
| 2010 |
/* |
| 2011 |
* Check if it is a temp table (presumably, of some other backend's). |
| 2012 |
* We cannot safely process other backends' temp tables. |
| 2013 |
*/ |
| 2014 |
if (classForm->relpersistence == RELPERSISTENCE_TEMP) |
| 2015 |
{ |
| 2016 |
/* |
| 2017 |
* We just ignore it if the owning backend is still active and |
| 2018 |
* using the temporary schema. Also, for safety, ignore it if the |
| 2019 |
* namespace doesn't exist or isn't a temp namespace after all. |
| 2020 |
*/ |
| 2021 |
if (checkTempNamespaceStatus(classForm->relnamespace) == TEMP_NAMESPACE_IDLE) |
| 2022 |
{ |
| 2023 |
/* |
| 2024 |
* The table seems to be orphaned -- although it might be that |
| 2025 |
* the owning backend has already deleted it and exited; our |
| 2026 |
* pg_class scan snapshot is not necessarily up-to-date |
| 2027 |
* anymore, so we could be looking at a committed-dead entry. |
| 2028 |
* Remember it so we can try to delete it later. |
| 2029 |
*/ |
| 2030 |
orphan_oids = lappend_oid(orphan_oids, relid); |
| 2031 |
} |
| 2032 |
continue; |
| 2033 |
} |
| 2034 |
|
| 2035 |
/* Fetch reloptions and the pgstat entry for this table */ |
| 2036 |
relopts = extract_autovac_opts(tuple, pg_class_desc); |
| 2037 |
tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared, |
| 2038 |
relid); |
| 2039 |
|
| 2040 |
/* Check if it needs vacuum or analyze */ |
| 2041 |
relation_needs_vacanalyze(relid, relopts, classForm, tabentry, |
| 2042 |
effective_multixact_freeze_max_age, |
| 2043 |
&dovacuum, &doanalyze, &wraparound); |
| 2044 |
|
| 2045 |
/* Relations that need work are added to table_oids */ |
| 2046 |
if (dovacuum || doanalyze) |
| 2047 |
table_oids = lappend_oid(table_oids, relid); |
| 2048 |
|
| 2049 |
/* |
| 2050 |
* Remember TOAST associations for the second pass. Note: we must do |
| 2051 |
* this whether or not the table is going to be vacuumed, because we |
| 2052 |
* don't automatically vacuum toast tables along the parent table. |
| 2053 |
*/ |
| 2054 |
if (OidIsValid(classForm->reltoastrelid)) |
| 2055 |
{ |
| 2056 |
av_relation *hentry; |
| 2057 |
bool found; |
| 2058 |
|
| 2059 |
hentry = hash_search(table_toast_map, |
| 2060 |
&classForm->reltoastrelid, |
| 2061 |
HASH_ENTER, &found); |
| 2062 |
|
| 2063 |
if (!found) |
| 2064 |
{ |
| 2065 |
/* hash_search already filled in the key */ |
| 2066 |
hentry->ar_relid = relid; |
| 2067 |
hentry->ar_hasrelopts = false; |
| 2068 |
if (relopts != NULL) |
| 2069 |
{ |
| 2070 |
hentry->ar_hasrelopts = true; |
| 2071 |
memcpy(&hentry->ar_reloptions, relopts, |
| 2072 |
sizeof(AutoVacOpts)); |
| 2073 |
} |
| 2074 |
} |
| 2075 |
} |
| 2076 |
|
| 2077 |
/* Release stuff to avoid per-relation leakage */ |
| 2078 |
if (relopts) |
| 2079 |
pfree(relopts); |
| 2080 |
if (tabentry) |
| 2081 |
pfree(tabentry); |
| 2082 |
} |
| 2083 |
|
| 2084 |
table_endscan(relScan); |
| 2085 |
|
| 2086 |
/* second pass: check TOAST tables */ |
| 2087 |
ScanKeyInit(&key, |
| 2088 |
Anum_pg_class_relkind, |
| 2089 |
BTEqualStrategyNumber, F_CHAREQ, |
| 2090 |
CharGetDatum(RELKIND_TOASTVALUE)); |
| 2091 |
|
| 2092 |
relScan = table_beginscan_catalog(classRel, 1, &key); |
| 2093 |
while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL) |
| 2094 |
{ |
| 2095 |
Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple); |
| 2096 |
PgStat_StatTabEntry *tabentry; |
| 2097 |
Oid relid; |
| 2098 |
AutoVacOpts *relopts; |
| 2099 |
bool free_relopts = false; |
| 2100 |
bool dovacuum; |
| 2101 |
bool doanalyze; |
| 2102 |
bool wraparound; |
| 2103 |
|
| 2104 |
/* |
| 2105 |
* We cannot safely process other backends' temp tables, so skip 'em. |
| 2106 |
*/ |
| 2107 |
if (classForm->relpersistence == RELPERSISTENCE_TEMP) |
| 2108 |
continue; |
| 2109 |
|
| 2110 |
relid = classForm->oid; |
| 2111 |
|
| 2112 |
/* |
| 2113 |
* fetch reloptions -- if this toast table does not have them, try the |
| 2114 |
* main rel |
| 2115 |
*/ |
| 2116 |
relopts = extract_autovac_opts(tuple, pg_class_desc); |
| 2117 |
if (relopts) |
| 2118 |
free_relopts = true; |
| 2119 |
else |
| 2120 |
{ |
| 2121 |
av_relation *hentry; |
| 2122 |
bool found; |
| 2123 |
|
| 2124 |
hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found); |
| 2125 |
if (found && hentry->ar_hasrelopts) |
| 2126 |
relopts = &hentry->ar_reloptions; |
| 2127 |
} |
| 2128 |
|
| 2129 |
/* Fetch the pgstat entry for this table */ |
| 2130 |
tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared, |
| 2131 |
relid); |
| 2132 |
|
| 2133 |
relation_needs_vacanalyze(relid, relopts, classForm, tabentry, |
| 2134 |
effective_multixact_freeze_max_age, |
| 2135 |
&dovacuum, &doanalyze, &wraparound); |
| 2136 |
|
| 2137 |
/* ignore analyze for toast tables */ |
| 2138 |
if (dovacuum) |
| 2139 |
table_oids = lappend_oid(table_oids, relid); |
| 2140 |
|
| 2141 |
/* Release stuff to avoid leakage */ |
| 2142 |
if (free_relopts) |
| 2143 |
pfree(relopts); |
| 2144 |
if (tabentry) |
| 2145 |
pfree(tabentry); |
| 2146 |
} |
| 2147 |
|
| 2148 |
table_endscan(relScan); |
| 2149 |
table_close(classRel, AccessShareLock); |
| 2150 |
|
| 2151 |
/* |
| 2152 |
* Recheck orphan temporary tables, and if they still seem orphaned, drop |
| 2153 |
* them. We'll eat a transaction per dropped table, which might seem |
| 2154 |
* excessive, but we should only need to do anything as a result of a |
| 2155 |
* previous backend crash, so this should not happen often enough to |
| 2156 |
* justify "optimizing". Using separate transactions ensures that we |
| 2157 |
* don't bloat the lock table if there are many temp tables to be dropped, |
| 2158 |
* and it ensures that we don't lose work if a deletion attempt fails. |
| 2159 |
*/ |
| 2160 |
foreach(cell, orphan_oids) |
| 2161 |
{ |
| 2162 |
Oid relid = lfirst_oid(cell); |
| 2163 |
Form_pg_class classForm; |
| 2164 |
ObjectAddress object; |
| 2165 |
|
| 2166 |
/* |
| 2167 |
* Check for user-requested abort. |
| 2168 |
*/ |
| 2169 |
CHECK_FOR_INTERRUPTS(); |
| 2170 |
|
| 2171 |
/* |
| 2172 |
* Try to lock the table. If we can't get the lock immediately, |
| 2173 |
* somebody else is using (or dropping) the table, so it's not our |
| 2174 |
* concern anymore. Having the lock prevents race conditions below. |
| 2175 |
*/ |
| 2176 |
if (!ConditionalLockRelationOid(relid, AccessExclusiveLock)) |
| 2177 |
continue; |
| 2178 |
|
| 2179 |
/* |
| 2180 |
* Re-fetch the pg_class tuple and re-check whether it still seems to |
| 2181 |
* be an orphaned temp table. If it's not there or no longer the same |
| 2182 |
* relation, ignore it. |
| 2183 |
*/ |
| 2184 |
tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid)); |
| 2185 |
if (!HeapTupleIsValid(tuple)) |
| 2186 |
{ |
| 2187 |
/* be sure to drop useless lock so we don't bloat lock table */ |
| 2188 |
UnlockRelationOid(relid, AccessExclusiveLock); |
| 2189 |
continue; |
| 2190 |
} |
| 2191 |
classForm = (Form_pg_class) GETSTRUCT(tuple); |
| 2192 |
|
| 2193 |
/* |
| 2194 |
* Make all the same tests made in the loop above. In event of OID |
| 2195 |
* counter wraparound, the pg_class entry we have now might be |
| 2196 |
* completely unrelated to the one we saw before. |
| 2197 |
*/ |
| 2198 |
if (!((classForm->relkind == RELKIND_RELATION || |
| 2199 |
classForm->relkind == RELKIND_MATVIEW) && |
| 2200 |
classForm->relpersistence == RELPERSISTENCE_TEMP)) |
| 2201 |
{ |
| 2202 |
UnlockRelationOid(relid, AccessExclusiveLock); |
| 2203 |
continue; |
| 2204 |
} |
| 2205 |
|
| 2206 |
if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE) |
| 2207 |
{ |
| 2208 |
UnlockRelationOid(relid, AccessExclusiveLock); |
| 2209 |
continue; |
| 2210 |
} |
| 2211 |
|
| 2212 |
/* |
| 2213 |
* Try to lock the temp namespace, too. Even though we have lock on |
| 2214 |
* the table itself, there's a risk of deadlock against an incoming |
| 2215 |
* backend trying to clean out the temp namespace, in case this table |
| 2216 |
* has dependencies (such as sequences) that the backend's |
| 2217 |
* performDeletion call might visit in a different order. If we can |
| 2218 |
* get AccessShareLock on the namespace, that's sufficient to ensure |
| 2219 |
* we're not running concurrently with RemoveTempRelations. If we |
| 2220 |
* can't, back off and let RemoveTempRelations do its thing. |
| 2221 |
*/ |
| 2222 |
if (!ConditionalLockDatabaseObject(NamespaceRelationId, |
| 2223 |
classForm->relnamespace, 0, |
| 2224 |
AccessShareLock)) |
| 2225 |
{ |
| 2226 |
UnlockRelationOid(relid, AccessExclusiveLock); |
| 2227 |
continue; |
| 2228 |
} |
| 2229 |
|
| 2230 |
/* OK, let's delete it */ |
| 2231 |
ereport(LOG, |
| 2232 |
(errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"", |
| 2233 |
get_database_name(MyDatabaseId), |
| 2234 |
get_namespace_name(classForm->relnamespace), |
| 2235 |
NameStr(classForm->relname)))); |
| 2236 |
|
| 2237 |
/* |
| 2238 |
* Deletion might involve TOAST table access, so ensure we have a |
| 2239 |
* valid snapshot. |
| 2240 |
*/ |
| 2241 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 2242 |
|
| 2243 |
object.classId = RelationRelationId; |
| 2244 |
object.objectId = relid; |
| 2245 |
object.objectSubId = 0; |
| 2246 |
performDeletion(&object, DROP_CASCADE, |
| 2247 |
PERFORM_DELETION_INTERNAL | |
| 2248 |
PERFORM_DELETION_QUIETLY | |
| 2249 |
PERFORM_DELETION_SKIP_EXTENSIONS); |
| 2250 |
|
| 2251 |
/* |
| 2252 |
* To commit the deletion, end current transaction and start a new |
| 2253 |
* one. Note this also releases the locks we took. |
| 2254 |
*/ |
| 2255 |
PopActiveSnapshot(); |
| 2256 |
CommitTransactionCommand(); |
| 2257 |
StartTransactionCommand(); |
| 2258 |
|
| 2259 |
/* StartTransactionCommand changed current memory context */ |
| 2260 |
MemoryContextSwitchTo(AutovacMemCxt); |
| 2261 |
} |
| 2262 |
|
| 2263 |
/* |
| 2264 |
* Optionally, create a buffer access strategy object for VACUUM to use. |
| 2265 |
* We use the same BufferAccessStrategy object for all tables VACUUMed by |
| 2266 |
* this worker to prevent autovacuum from blowing out shared buffers. |
| 2267 |
* |
| 2268 |
* VacuumBufferUsageLimit being set to 0 results in |
| 2269 |
* GetAccessStrategyWithSize returning NULL, effectively meaning we can |
| 2270 |
* use up to all of shared buffers. |
| 2271 |
* |
| 2272 |
* If we later enter failsafe mode on any of the tables being vacuumed, we |
| 2273 |
* will cease use of the BufferAccessStrategy only for that table. |
| 2274 |
* |
| 2275 |
* XXX should we consider adding code to adjust the size of this if |
| 2276 |
* VacuumBufferUsageLimit changes? |
| 2277 |
*/ |
| 2278 |
bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, VacuumBufferUsageLimit); |
| 2279 |
|
| 2280 |
/* |
| 2281 |
* create a memory context to act as fake PortalContext, so that the |
| 2282 |
* contexts created in the vacuum code are cleaned up for each table. |
| 2283 |
*/ |
| 2284 |
PortalContext = AllocSetContextCreate(AutovacMemCxt, |
| 2285 |
"Autovacuum Portal", |
| 2286 |
ALLOCSET_DEFAULT_SIZES); |
| 2287 |
|
| 2288 |
/* |
| 2289 |
* Perform operations on collected tables. |
| 2290 |
*/ |
| 2291 |
foreach(cell, table_oids) |
| 2292 |
{ |
| 2293 |
Oid relid = lfirst_oid(cell); |
| 2294 |
HeapTuple classTup; |
| 2295 |
autovac_table *tab; |
| 2296 |
bool isshared; |
| 2297 |
bool skipit; |
| 2298 |
dlist_iter iter; |
| 2299 |
|
| 2300 |
CHECK_FOR_INTERRUPTS(); |
| 2301 |
|
| 2302 |
/* |
| 2303 |
* Check for config changes before processing each collected table. |
| 2304 |
*/ |
| 2305 |
if (ConfigReloadPending) |
| 2306 |
{ |
| 2307 |
ConfigReloadPending = false; |
| 2308 |
ProcessConfigFile(PGC_SIGHUP); |
| 2309 |
|
| 2310 |
/* |
| 2311 |
* You might be tempted to bail out if we see autovacuum is now |
| 2312 |
* disabled. Must resist that temptation -- this might be a |
| 2313 |
* for-wraparound emergency worker, in which case that would be |
| 2314 |
* entirely inappropriate. |
| 2315 |
*/ |
| 2316 |
} |
| 2317 |
|
| 2318 |
/* |
| 2319 |
* Find out whether the table is shared or not. (It's slightly |
| 2320 |
* annoying to fetch the syscache entry just for this, but in typical |
| 2321 |
* cases it adds little cost because table_recheck_autovac would |
| 2322 |
* refetch the entry anyway. We could buy that back by copying the |
| 2323 |
* tuple here and passing it to table_recheck_autovac, but that |
| 2324 |
* increases the odds of that function working with stale data.) |
| 2325 |
*/ |
| 2326 |
classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); |
| 2327 |
if (!HeapTupleIsValid(classTup)) |
| 2328 |
continue; /* somebody deleted the rel, forget it */ |
| 2329 |
isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared; |
| 2330 |
ReleaseSysCache(classTup); |
| 2331 |
|
| 2332 |
/* |
| 2333 |
* Hold schedule lock from here until we've claimed the table. We |
| 2334 |
* also need the AutovacuumLock to walk the worker array, but that one |
| 2335 |
* can just be a shared lock. |
| 2336 |
*/ |
| 2337 |
LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE); |
| 2338 |
LWLockAcquire(AutovacuumLock, LW_SHARED); |
| 2339 |
|
| 2340 |
/* |
| 2341 |
* Check whether the table is being vacuumed concurrently by another |
| 2342 |
* worker. |
| 2343 |
*/ |
| 2344 |
skipit = false; |
| 2345 |
dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers) |
| 2346 |
{ |
| 2347 |
WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur); |
| 2348 |
|
| 2349 |
/* ignore myself */ |
| 2350 |
if (worker == MyWorkerInfo) |
| 2351 |
continue; |
| 2352 |
|
| 2353 |
/* ignore workers in other databases (unless table is shared) */ |
| 2354 |
if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId) |
| 2355 |
continue; |
| 2356 |
|
| 2357 |
if (worker->wi_tableoid == relid) |
| 2358 |
{ |
| 2359 |
skipit = true; |
| 2360 |
found_concurrent_worker = true; |
| 2361 |
break; |
| 2362 |
} |
| 2363 |
} |
| 2364 |
LWLockRelease(AutovacuumLock); |
| 2365 |
if (skipit) |
| 2366 |
{ |
| 2367 |
LWLockRelease(AutovacuumScheduleLock); |
| 2368 |
continue; |
| 2369 |
} |
| 2370 |
|
| 2371 |
/* |
| 2372 |
* Store the table's OID in shared memory before releasing the |
| 2373 |
* schedule lock, so that other workers don't try to vacuum it |
| 2374 |
* concurrently. (We claim it here so as not to hold |
| 2375 |
* AutovacuumScheduleLock while rechecking the stats.) |
| 2376 |
*/ |
| 2377 |
MyWorkerInfo->wi_tableoid = relid; |
| 2378 |
MyWorkerInfo->wi_sharedrel = isshared; |
| 2379 |
LWLockRelease(AutovacuumScheduleLock); |
| 2380 |
|
| 2381 |
/* |
| 2382 |
* Check whether pgstat data still says we need to vacuum this table. |
| 2383 |
* It could have changed if something else processed the table while |
| 2384 |
* we weren't looking. This doesn't entirely close the race condition, |
| 2385 |
* but it is very small. |
| 2386 |
*/ |
| 2387 |
MemoryContextSwitchTo(AutovacMemCxt); |
| 2388 |
tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc, |
| 2389 |
effective_multixact_freeze_max_age); |
| 2390 |
if (tab == NULL) |
| 2391 |
{ |
| 2392 |
/* someone else vacuumed the table, or it went away */ |
| 2393 |
LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE); |
| 2394 |
MyWorkerInfo->wi_tableoid = InvalidOid; |
| 2395 |
MyWorkerInfo->wi_sharedrel = false; |
| 2396 |
LWLockRelease(AutovacuumScheduleLock); |
| 2397 |
continue; |
| 2398 |
} |
| 2399 |
|
| 2400 |
/* |
| 2401 |
* Save the cost-related storage parameter values in global variables |
| 2402 |
* for reference when updating vacuum_cost_delay and vacuum_cost_limit |
| 2403 |
* during vacuuming this table. |
| 2404 |
*/ |
| 2405 |
av_storage_param_cost_delay = tab->at_storage_param_vac_cost_delay; |
| 2406 |
av_storage_param_cost_limit = tab->at_storage_param_vac_cost_limit; |
| 2407 |
|
| 2408 |
/* |
| 2409 |
* We only expect this worker to ever set the flag, so don't bother |
| 2410 |
* checking the return value. We shouldn't have to retry. |
| 2411 |
*/ |
| 2412 |
if (tab->at_dobalance) |
| 2413 |
pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance); |
| 2414 |
else |
| 2415 |
pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance); |
| 2416 |
|
| 2417 |
LWLockAcquire(AutovacuumLock, LW_SHARED); |
| 2418 |
autovac_recalculate_workers_for_balance(); |
| 2419 |
LWLockRelease(AutovacuumLock); |
| 2420 |
|
| 2421 |
/* |
| 2422 |
* We wait until this point to update cost delay and cost limit |
| 2423 |
* values, even though we reloaded the configuration file above, so |
| 2424 |
* that we can take into account the cost-related storage parameters. |
| 2425 |
*/ |
| 2426 |
VacuumUpdateCosts(); |
| 2427 |
|
| 2428 |
|
| 2429 |
/* clean up memory before each iteration */ |
| 2430 |
MemoryContextReset(PortalContext); |
| 2431 |
|
| 2432 |
/* |
| 2433 |
* Save the relation name for a possible error message, to avoid a |
| 2434 |
* catalog lookup in case of an error. If any of these return NULL, |
| 2435 |
* then the relation has been dropped since last we checked; skip it. |
| 2436 |
* Note: they must live in a long-lived memory context because we call |
| 2437 |
* vacuum and analyze in different transactions. |
| 2438 |
*/ |
| 2439 |
|
| 2440 |
tab->at_relname = get_rel_name(tab->at_relid); |
| 2441 |
tab->at_nspname = get_namespace_name(get_rel_namespace(tab->at_relid)); |
| 2442 |
tab->at_datname = get_database_name(MyDatabaseId); |
| 2443 |
if (!tab->at_relname || !tab->at_nspname || !tab->at_datname) |
| 2444 |
goto deleted; |
| 2445 |
|
| 2446 |
/* |
| 2447 |
* We will abort vacuuming the current table if something errors out, |
| 2448 |
* and continue with the next one in schedule; in particular, this |
| 2449 |
* happens if we are interrupted with SIGINT. |
| 2450 |
*/ |
| 2451 |
PG_TRY(); |
| 2452 |
{ |
| 2453 |
/* Use PortalContext for any per-table allocations */ |
| 2454 |
MemoryContextSwitchTo(PortalContext); |
| 2455 |
|
| 2456 |
/* have at it */ |
| 2457 |
autovacuum_do_vac_analyze(tab, bstrategy); |
| 2458 |
|
| 2459 |
/* |
| 2460 |
* Clear a possible query-cancel signal, to avoid a late reaction |
| 2461 |
* to an automatically-sent signal because of vacuuming the |
| 2462 |
* current table (we're done with it, so it would make no sense to |
| 2463 |
* cancel at this point.) |
| 2464 |
*/ |
| 2465 |
QueryCancelPending = false; |
| 2466 |
} |
| 2467 |
PG_CATCH(); |
| 2468 |
{ |
| 2469 |
/* |
| 2470 |
* Abort the transaction, start a new one, and proceed with the |
| 2471 |
* next table in our list. |
| 2472 |
*/ |
| 2473 |
HOLD_INTERRUPTS(); |
| 2474 |
if (tab->at_params.options & VACOPT_VACUUM) |
| 2475 |
errcontext("automatic vacuum of table \"%s.%s.%s\"", |
| 2476 |
tab->at_datname, tab->at_nspname, tab->at_relname); |
| 2477 |
else |
| 2478 |
errcontext("automatic analyze of table \"%s.%s.%s\"", |
| 2479 |
tab->at_datname, tab->at_nspname, tab->at_relname); |
| 2480 |
EmitErrorReport(); |
| 2481 |
|
| 2482 |
/* this resets ProcGlobal->statusFlags[i] too */ |
| 2483 |
AbortOutOfAnyTransaction(); |
| 2484 |
FlushErrorState(); |
| 2485 |
MemoryContextReset(PortalContext); |
| 2486 |
|
| 2487 |
/* restart our transaction for the following operations */ |
| 2488 |
StartTransactionCommand(); |
| 2489 |
RESUME_INTERRUPTS(); |
| 2490 |
} |
| 2491 |
PG_END_TRY(); |
| 2492 |
|
| 2493 |
/* Make sure we're back in AutovacMemCxt */ |
| 2494 |
MemoryContextSwitchTo(AutovacMemCxt); |
| 2495 |
|
| 2496 |
did_vacuum = true; |
| 2497 |
|
| 2498 |
/* ProcGlobal->statusFlags[i] are reset at the next end of xact */ |
| 2499 |
|
| 2500 |
/* be tidy */ |
| 2501 |
deleted: |
| 2502 |
if (tab->at_datname != NULL) |
| 2503 |
pfree(tab->at_datname); |
| 2504 |
if (tab->at_nspname != NULL) |
| 2505 |
pfree(tab->at_nspname); |
| 2506 |
if (tab->at_relname != NULL) |
| 2507 |
pfree(tab->at_relname); |
| 2508 |
pfree(tab); |
| 2509 |
|
| 2510 |
/* |
| 2511 |
* Remove my info from shared memory. We set wi_dobalance on the |
| 2512 |
* assumption that we are more likely than not to vacuum a table with |
| 2513 |
* no cost-related storage parameters next, so we want to claim our |
| 2514 |
* share of I/O as soon as possible to avoid thrashing the global |
| 2515 |
* balance. |
| 2516 |
*/ |
| 2517 |
LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE); |
| 2518 |
MyWorkerInfo->wi_tableoid = InvalidOid; |
| 2519 |
MyWorkerInfo->wi_sharedrel = false; |
| 2520 |
LWLockRelease(AutovacuumScheduleLock); |
| 2521 |
pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance); |
| 2522 |
} |
| 2523 |
|
| 2524 |
list_free(table_oids); |
| 2525 |
|
| 2526 |
/* |
| 2527 |
* Perform additional work items, as requested by backends. |
| 2528 |
*/ |
| 2529 |
LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); |
| 2530 |
for (i = 0; i < NUM_WORKITEMS; i++) |
| 2531 |
{ |
| 2532 |
AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i]; |
| 2533 |
|
| 2534 |
if (!workitem->avw_used) |
| 2535 |
continue; |
| 2536 |
if (workitem->avw_active) |
| 2537 |
continue; |
| 2538 |
if (workitem->avw_database != MyDatabaseId) |
| 2539 |
continue; |
| 2540 |
|
| 2541 |
/* claim this one, and release lock while performing it */ |
| 2542 |
workitem->avw_active = true; |
| 2543 |
LWLockRelease(AutovacuumLock); |
| 2544 |
|
| 2545 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 2546 |
perform_work_item(workitem); |
| 2547 |
if (ActiveSnapshotSet()) /* transaction could have aborted */ |
| 2548 |
PopActiveSnapshot(); |
| 2549 |
|
| 2550 |
/* |
| 2551 |
* Check for config changes before acquiring lock for further jobs. |
| 2552 |
*/ |
| 2553 |
CHECK_FOR_INTERRUPTS(); |
| 2554 |
if (ConfigReloadPending) |
| 2555 |
{ |
| 2556 |
ConfigReloadPending = false; |
| 2557 |
ProcessConfigFile(PGC_SIGHUP); |
| 2558 |
VacuumUpdateCosts(); |
| 2559 |
} |
| 2560 |
|
| 2561 |
LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); |
| 2562 |
|
| 2563 |
/* and mark it done */ |
| 2564 |
workitem->avw_active = false; |
| 2565 |
workitem->avw_used = false; |
| 2566 |
} |
| 2567 |
LWLockRelease(AutovacuumLock); |
| 2568 |
|
| 2569 |
/* |
| 2570 |
* We leak table_toast_map here (among other things), but since we're |
| 2571 |
* going away soon, it's not a problem. |
| 2572 |
*/ |
| 2573 |
|
| 2574 |
/* |
| 2575 |
* Update pg_database.datfrozenxid, and truncate pg_xact if possible. We |
| 2576 |
* only need to do this once, not after each table. |
| 2577 |
* |
| 2578 |
* Even if we didn't vacuum anything, it may still be important to do |
| 2579 |
* this, because one indirect effect of vac_update_datfrozenxid() is to |
| 2580 |
* update TransamVariables->xidVacLimit. That might need to be done even |
| 2581 |
* if we haven't vacuumed anything, because relations with older |
| 2582 |
* relfrozenxid values or other databases with older datfrozenxid values |
| 2583 |
* might have been dropped, allowing xidVacLimit to advance. |
| 2584 |
* |
| 2585 |
* However, it's also important not to do this blindly in all cases, |
| 2586 |
* because when autovacuum=off this will restart the autovacuum launcher. |
| 2587 |
* If we're not careful, an infinite loop can result, where workers find |
| 2588 |
* no work to do and restart the launcher, which starts another worker in |
| 2589 |
* the same database that finds no work to do. To prevent that, we skip |
| 2590 |
* this if (1) we found no work to do and (2) we skipped at least one |
| 2591 |
* table due to concurrent autovacuum activity. In that case, the other |
| 2592 |
* worker has already done it, or will do so when it finishes. |
| 2593 |
*/ |
| 2594 |
if (did_vacuum || !found_concurrent_worker) |
| 2595 |
vac_update_datfrozenxid(); |
| 2596 |
|
| 2597 |
/* Finally close out the last transaction. */ |
| 2598 |
CommitTransactionCommand(); |
| 2599 |
} |
| 2600 |
|
| 2601 |
/* |
| 2602 |
* Execute a previously registered work item. |
| 2603 |
*/ |
| 2604 |
static void |
| 2605 |
perform_work_item(AutoVacuumWorkItem *workitem) |
| 2606 |
{ |
| 2607 |
char *cur_datname = NULL; |
| 2608 |
char *cur_nspname = NULL; |
| 2609 |
char *cur_relname = NULL; |
| 2610 |
|
| 2611 |
/* |
| 2612 |
* Note we do not store table info in MyWorkerInfo, since this is not |
| 2613 |
* vacuuming proper. |
| 2614 |
*/ |
| 2615 |
|
| 2616 |
/* |
| 2617 |
* Save the relation name for a possible error message, to avoid a catalog |
| 2618 |
* lookup in case of an error. If any of these return NULL, then the |
| 2619 |
* relation has been dropped since last we checked; skip it. |
| 2620 |
*/ |
| 2621 |
Assert(CurrentMemoryContext == AutovacMemCxt); |
| 2622 |
|
| 2623 |
cur_relname = get_rel_name(workitem->avw_relation); |
| 2624 |
cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation)); |
| 2625 |
cur_datname = get_database_name(MyDatabaseId); |
| 2626 |
if (!cur_relname || !cur_nspname || !cur_datname) |
| 2627 |
goto deleted2; |
| 2628 |
|
| 2629 |
autovac_report_workitem(workitem, cur_nspname, cur_relname); |
| 2630 |
|
| 2631 |
/* clean up memory before each work item */ |
| 2632 |
MemoryContextReset(PortalContext); |
| 2633 |
|
| 2634 |
/* |
| 2635 |
* We will abort the current work item if something errors out, and |
| 2636 |
* continue with the next one; in particular, this happens if we are |
| 2637 |
* interrupted with SIGINT. Note that this means that the work item list |
| 2638 |
* can be lossy. |
| 2639 |
*/ |
| 2640 |
PG_TRY(); |
| 2641 |
{ |
| 2642 |
/* Use PortalContext for any per-work-item allocations */ |
| 2643 |
MemoryContextSwitchTo(PortalContext); |
| 2644 |
|
| 2645 |
/* |
| 2646 |
* Have at it. Functions called here are responsible for any required |
| 2647 |
* user switch and sandbox. |
| 2648 |
*/ |
| 2649 |
switch (workitem->avw_type) |
| 2650 |
{ |
| 2651 |
case AVW_BRINSummarizeRange: |
| 2652 |
DirectFunctionCall2(brin_summarize_range, |
| 2653 |
ObjectIdGetDatum(workitem->avw_relation), |
| 2654 |
Int64GetDatum((int64) workitem->avw_blockNumber)); |
| 2655 |
break; |
| 2656 |
default: |
| 2657 |
elog(WARNING, "unrecognized work item found: type %d", |
| 2658 |
workitem->avw_type); |
| 2659 |
break; |
| 2660 |
} |
| 2661 |
|
| 2662 |
/* |
| 2663 |
* Clear a possible query-cancel signal, to avoid a late reaction to |
| 2664 |
* an automatically-sent signal because of vacuuming the current table |
| 2665 |
* (we're done with it, so it would make no sense to cancel at this |
| 2666 |
* point.) |
| 2667 |
*/ |
| 2668 |
QueryCancelPending = false; |
| 2669 |
} |
| 2670 |
PG_CATCH(); |
| 2671 |
{ |
| 2672 |
/* |
| 2673 |
* Abort the transaction, start a new one, and proceed with the next |
| 2674 |
* table in our list. |
| 2675 |
*/ |
| 2676 |
HOLD_INTERRUPTS(); |
| 2677 |
errcontext("processing work entry for relation \"%s.%s.%s\"", |
| 2678 |
cur_datname, cur_nspname, cur_relname); |
| 2679 |
EmitErrorReport(); |
| 2680 |
|
| 2681 |
/* this resets ProcGlobal->statusFlags[i] too */ |
| 2682 |
AbortOutOfAnyTransaction(); |
| 2683 |
FlushErrorState(); |
| 2684 |
MemoryContextReset(PortalContext); |
| 2685 |
|
| 2686 |
/* restart our transaction for the following operations */ |
| 2687 |
StartTransactionCommand(); |
| 2688 |
RESUME_INTERRUPTS(); |
| 2689 |
} |
| 2690 |
PG_END_TRY(); |
| 2691 |
|
| 2692 |
/* Make sure we're back in AutovacMemCxt */ |
| 2693 |
MemoryContextSwitchTo(AutovacMemCxt); |
| 2694 |
|
| 2695 |
/* We intentionally do not set did_vacuum here */ |
| 2696 |
|
| 2697 |
/* be tidy */ |
| 2698 |
deleted2: |
| 2699 |
if (cur_datname) |
| 2700 |
pfree(cur_datname); |
| 2701 |
if (cur_nspname) |
| 2702 |
pfree(cur_nspname); |
| 2703 |
if (cur_relname) |
| 2704 |
pfree(cur_relname); |
| 2705 |
} |
| 2706 |
|
| 2707 |
/* |
| 2708 |
* extract_autovac_opts |
| 2709 |
* |
| 2710 |
* Given a relation's pg_class tuple, return a palloc'd copy of the |
| 2711 |
* AutoVacOpts portion of reloptions, if set; otherwise, return NULL. |
| 2712 |
* |
| 2713 |
* Note: callers do not have a relation lock on the table at this point, |
| 2714 |
* so the table could have been dropped, and its catalog rows gone, after |
| 2715 |
* we acquired the pg_class row. If pg_class had a TOAST table, this would |
| 2716 |
* be a risk; fortunately, it doesn't. |
| 2717 |
*/ |
| 2718 |
static AutoVacOpts * |
| 2719 |
extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc) |
| 2720 |
{ |
| 2721 |
bytea *relopts; |
| 2722 |
AutoVacOpts *av; |
| 2723 |
|
| 2724 |
Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION || |
| 2725 |
((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW || |
| 2726 |
((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE); |
| 2727 |
|
| 2728 |
relopts = extractRelOptions(tup, pg_class_desc, NULL); |
| 2729 |
if (relopts == NULL) |
| 2730 |
return NULL; |
| 2731 |
|
| 2732 |
av = palloc(sizeof(AutoVacOpts)); |
| 2733 |
memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts)); |
| 2734 |
pfree(relopts); |
| 2735 |
|
| 2736 |
return av; |
| 2737 |
} |
| 2738 |
|
| 2739 |
|
| 2740 |
/* |
| 2741 |
* table_recheck_autovac |
| 2742 |
* |
| 2743 |
* Recheck whether a table still needs vacuum or analyze. Return value is a |
| 2744 |
* valid autovac_table pointer if it does, NULL otherwise. |
| 2745 |
* |
| 2746 |
* Note that the returned autovac_table does not have the name fields set. |
| 2747 |
*/ |
| 2748 |
static autovac_table * |
| 2749 |
table_recheck_autovac(Oid relid, HTAB *table_toast_map, |
| 2750 |
TupleDesc pg_class_desc, |
| 2751 |
int effective_multixact_freeze_max_age) |
| 2752 |
{ |
| 2753 |
Form_pg_class classForm; |
| 2754 |
HeapTuple classTup; |
| 2755 |
bool dovacuum; |
| 2756 |
bool doanalyze; |
| 2757 |
autovac_table *tab = NULL; |
| 2758 |
bool wraparound; |
| 2759 |
AutoVacOpts *avopts; |
| 2760 |
bool free_avopts = false; |
| 2761 |
|
| 2762 |
/* fetch the relation's relcache entry */ |
| 2763 |
classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid)); |
| 2764 |
if (!HeapTupleIsValid(classTup)) |
| 2765 |
return NULL; |
| 2766 |
classForm = (Form_pg_class) GETSTRUCT(classTup); |
| 2767 |
|
| 2768 |
/* |
| 2769 |
* Get the applicable reloptions. If it is a TOAST table, try to get the |
| 2770 |
* main table reloptions if the toast table itself doesn't have. |
| 2771 |
*/ |
| 2772 |
avopts = extract_autovac_opts(classTup, pg_class_desc); |
| 2773 |
if (avopts) |
| 2774 |
free_avopts = true; |
| 2775 |
else if (classForm->relkind == RELKIND_TOASTVALUE && |
| 2776 |
table_toast_map != NULL) |
| 2777 |
{ |
| 2778 |
av_relation *hentry; |
| 2779 |
bool found; |
| 2780 |
|
| 2781 |
hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found); |
| 2782 |
if (found && hentry->ar_hasrelopts) |
| 2783 |
avopts = &hentry->ar_reloptions; |
| 2784 |
} |
| 2785 |
|
| 2786 |
recheck_relation_needs_vacanalyze(relid, avopts, classForm, |
| 2787 |
effective_multixact_freeze_max_age, |
| 2788 |
&dovacuum, &doanalyze, &wraparound); |
| 2789 |
|
| 2790 |
/* OK, it needs something done */ |
| 2791 |
if (doanalyze || dovacuum) |
| 2792 |
{ |
| 2793 |
int freeze_min_age; |
| 2794 |
int freeze_table_age; |
| 2795 |
int multixact_freeze_min_age; |
| 2796 |
int multixact_freeze_table_age; |
| 2797 |
int log_min_duration; |
| 2798 |
|
| 2799 |
/* |
| 2800 |
* Calculate the vacuum cost parameters and the freeze ages. If there |
| 2801 |
* are options set in pg_class.reloptions, use them; in the case of a |
| 2802 |
* toast table, try the main table too. Otherwise use the GUC |
| 2803 |
* defaults, autovacuum's own first and plain vacuum second. |
| 2804 |
*/ |
| 2805 |
|
| 2806 |
/* -1 in autovac setting means use log_autovacuum_min_duration */ |
| 2807 |
log_min_duration = (avopts && avopts->log_min_duration >= 0) |
| 2808 |
? avopts->log_min_duration |
| 2809 |
: Log_autovacuum_min_duration; |
| 2810 |
|
| 2811 |
/* these do not have autovacuum-specific settings */ |
| 2812 |
freeze_min_age = (avopts && avopts->freeze_min_age >= 0) |
| 2813 |
? avopts->freeze_min_age |
| 2814 |
: default_freeze_min_age; |
| 2815 |
|
| 2816 |
freeze_table_age = (avopts && avopts->freeze_table_age >= 0) |
| 2817 |
? avopts->freeze_table_age |
| 2818 |
: default_freeze_table_age; |
| 2819 |
|
| 2820 |
multixact_freeze_min_age = (avopts && |
| 2821 |
avopts->multixact_freeze_min_age >= 0) |
| 2822 |
? avopts->multixact_freeze_min_age |
| 2823 |
: default_multixact_freeze_min_age; |
| 2824 |
|
| 2825 |
multixact_freeze_table_age = (avopts && |
| 2826 |
avopts->multixact_freeze_table_age >= 0) |
| 2827 |
? avopts->multixact_freeze_table_age |
| 2828 |
: default_multixact_freeze_table_age; |
| 2829 |
|
| 2830 |
tab = palloc(sizeof(autovac_table)); |
| 2831 |
tab->at_relid = relid; |
| 2832 |
tab->at_sharedrel = classForm->relisshared; |
| 2833 |
|
| 2834 |
/* |
| 2835 |
* Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so |
| 2836 |
* that vacuum() skips toast relations. Also note we tell vacuum() to |
| 2837 |
* skip vac_update_datfrozenxid(); we'll do that separately. |
| 2838 |
*/ |
| 2839 |
tab->at_params.options = |
| 2840 |
(dovacuum ? (VACOPT_VACUUM | |
| 2841 |
VACOPT_PROCESS_MAIN | |
| 2842 |
VACOPT_SKIP_DATABASE_STATS) : 0) | |
| 2843 |
(doanalyze ? VACOPT_ANALYZE : 0) | |
| 2844 |
(!wraparound ? VACOPT_SKIP_LOCKED : 0); |
| 2845 |
|
| 2846 |
/* |
| 2847 |
* index_cleanup and truncate are unspecified at first in autovacuum. |
| 2848 |
* They will be filled in with usable values using their reloptions |
| 2849 |
* (or reloption defaults) later. |
| 2850 |
*/ |
| 2851 |
tab->at_params.index_cleanup = VACOPTVALUE_UNSPECIFIED; |
| 2852 |
tab->at_params.truncate = VACOPTVALUE_UNSPECIFIED; |
| 2853 |
/* As of now, we don't support parallel vacuum for autovacuum */ |
| 2854 |
tab->at_params.nworkers = -1; |
| 2855 |
tab->at_params.freeze_min_age = freeze_min_age; |
| 2856 |
tab->at_params.freeze_table_age = freeze_table_age; |
| 2857 |
tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age; |
| 2858 |
tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age; |
| 2859 |
tab->at_params.is_wraparound = wraparound; |
| 2860 |
tab->at_params.log_min_duration = log_min_duration; |
| 2861 |
tab->at_params.toast_parent = InvalidOid; |
| 2862 |
|
| 2863 |
/* |
| 2864 |
* Later, in vacuum_rel(), we check reloptions for any |
| 2865 |
* vacuum_max_eager_freeze_failure_rate override. |
| 2866 |
*/ |
| 2867 |
tab->at_params.max_eager_freeze_failure_rate = vacuum_max_eager_freeze_failure_rate; |
| 2868 |
tab->at_storage_param_vac_cost_limit = avopts ? |
| 2869 |
avopts->vacuum_cost_limit : 0; |
| 2870 |
tab->at_storage_param_vac_cost_delay = avopts ? |
| 2871 |
avopts->vacuum_cost_delay : -1; |
| 2872 |
tab->at_relname = NULL; |
| 2873 |
tab->at_nspname = NULL; |
| 2874 |
tab->at_datname = NULL; |
| 2875 |
|
| 2876 |
/* |
| 2877 |
* If any of the cost delay parameters has been set individually for |
| 2878 |
* this table, disable the balancing algorithm. |
| 2879 |
*/ |
| 2880 |
tab->at_dobalance = |
| 2881 |
!(avopts && (avopts->vacuum_cost_limit > 0 || |
| 2882 |
avopts->vacuum_cost_delay >= 0)); |
| 2883 |
} |
| 2884 |
|
| 2885 |
if (free_avopts) |
| 2886 |
pfree(avopts); |
| 2887 |
heap_freetuple(classTup); |
| 2888 |
return tab; |
| 2889 |
} |
| 2890 |
|
| 2891 |
/* |
| 2892 |
* recheck_relation_needs_vacanalyze |
| 2893 |
* |
| 2894 |
* Subroutine for table_recheck_autovac. |
| 2895 |
* |
| 2896 |
* Fetch the pgstat of a relation and recheck whether a relation |
| 2897 |
* needs to be vacuumed or analyzed. |
| 2898 |
*/ |
| 2899 |
static void |
| 2900 |
recheck_relation_needs_vacanalyze(Oid relid, |
| 2901 |
AutoVacOpts *avopts, |
| 2902 |
Form_pg_class classForm, |
| 2903 |
int effective_multixact_freeze_max_age, |
| 2904 |
bool *dovacuum, |
| 2905 |
bool *doanalyze, |
| 2906 |
bool *wraparound) |
| 2907 |
{ |
| 2908 |
PgStat_StatTabEntry *tabentry; |
| 2909 |
|
| 2910 |
/* fetch the pgstat table entry */ |
| 2911 |
tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared, |
| 2912 |
relid); |
| 2913 |
|
| 2914 |
relation_needs_vacanalyze(relid, avopts, classForm, tabentry, |
| 2915 |
effective_multixact_freeze_max_age, |
| 2916 |
dovacuum, doanalyze, wraparound); |
| 2917 |
|
| 2918 |
/* Release tabentry to avoid leakage */ |
| 2919 |
if (tabentry) |
| 2920 |
pfree(tabentry); |
| 2921 |
|
| 2922 |
/* ignore ANALYZE for toast tables */ |
| 2923 |
if (classForm->relkind == RELKIND_TOASTVALUE) |
| 2924 |
*doanalyze = false; |
| 2925 |
} |
| 2926 |
|
| 2927 |
/* |
| 2928 |
* relation_needs_vacanalyze |
| 2929 |
* |
| 2930 |
* Check whether a relation needs to be vacuumed or analyzed; return each into |
| 2931 |
* "dovacuum" and "doanalyze", respectively. Also return whether the vacuum is |
| 2932 |
* being forced because of Xid or multixact wraparound. |
| 2933 |
* |
| 2934 |
* relopts is a pointer to the AutoVacOpts options (either for itself in the |
| 2935 |
* case of a plain table, or for either itself or its parent table in the case |
| 2936 |
* of a TOAST table), NULL if none; tabentry is the pgstats entry, which can be |
| 2937 |
* NULL. |
| 2938 |
* |
| 2939 |
* A table needs to be vacuumed if the number of dead tuples exceeds a |
| 2940 |
* threshold. This threshold is calculated as |
| 2941 |
* |
| 2942 |
* threshold = vac_base_thresh + vac_scale_factor * reltuples |
| 2943 |
* if (threshold > vac_max_thresh) |
| 2944 |
* threshold = vac_max_thresh; |
| 2945 |
* |
| 2946 |
* For analyze, the analysis done is that the number of tuples inserted, |
| 2947 |
* deleted and updated since the last analyze exceeds a threshold calculated |
| 2948 |
* in the same fashion as above. Note that the cumulative stats system stores |
| 2949 |
* the number of tuples (both live and dead) that there were as of the last |
| 2950 |
* analyze. This is asymmetric to the VACUUM case. |
| 2951 |
* |
| 2952 |
* We also force vacuum if the table's relfrozenxid is more than freeze_max_age |
| 2953 |
* transactions back, and if its relminmxid is more than |
| 2954 |
* multixact_freeze_max_age multixacts back. |
| 2955 |
* |
| 2956 |
* A table whose autovacuum_enabled option is false is |
| 2957 |
* automatically skipped (unless we have to vacuum it due to freeze_max_age). |
| 2958 |
* Thus autovacuum can be disabled for specific tables. Also, when the cumulative |
| 2959 |
* stats system does not have data about a table, it will be skipped. |
| 2960 |
* |
| 2961 |
* A table whose vac_base_thresh value is < 0 takes the base value from the |
| 2962 |
* autovacuum_vacuum_threshold GUC variable. Similarly, a vac_scale_factor |
| 2963 |
* value < 0 is substituted with the value of |
| 2964 |
* autovacuum_vacuum_scale_factor GUC variable. Ditto for analyze. |
| 2965 |
*/ |
| 2966 |
static void |
| 2967 |
relation_needs_vacanalyze(Oid relid, |
| 2968 |
AutoVacOpts *relopts, |
| 2969 |
Form_pg_class classForm, |
| 2970 |
PgStat_StatTabEntry *tabentry, |
| 2971 |
int effective_multixact_freeze_max_age, |
| 2972 |
/* output params below */ |
| 2973 |
bool *dovacuum, |
| 2974 |
bool *doanalyze, |
| 2975 |
bool *wraparound) |
| 2976 |
{ |
| 2977 |
bool force_vacuum; |
| 2978 |
bool av_enabled; |
| 2979 |
|
| 2980 |
/* constants from reloptions or GUC variables */ |
| 2981 |
int vac_base_thresh, |
| 2982 |
vac_max_thresh, |
| 2983 |
vac_ins_base_thresh, |
| 2984 |
anl_base_thresh; |
| 2985 |
float4 vac_scale_factor, |
| 2986 |
vac_ins_scale_factor, |
| 2987 |
anl_scale_factor; |
| 2988 |
|
| 2989 |
/* thresholds calculated from above constants */ |
| 2990 |
float4 vacthresh, |
| 2991 |
vacinsthresh, |
| 2992 |
anlthresh; |
| 2993 |
|
| 2994 |
/* number of vacuum (resp. analyze) tuples at this time */ |
| 2995 |
float4 vactuples, |
| 2996 |
instuples, |
| 2997 |
anltuples; |
| 2998 |
|
| 2999 |
/* freeze parameters */ |
| 3000 |
int freeze_max_age; |
| 3001 |
int multixact_freeze_max_age; |
| 3002 |
TransactionId xidForceLimit; |
| 3003 |
TransactionId relfrozenxid; |
| 3004 |
MultiXactId multiForceLimit; |
| 3005 |
|
| 3006 |
Assert(classForm != NULL); |
| 3007 |
Assert(OidIsValid(relid)); |
| 3008 |
|
| 3009 |
/* |
| 3010 |
* Determine vacuum/analyze equation parameters. We have two possible |
| 3011 |
* sources: the passed reloptions (which could be a main table or a toast |
| 3012 |
* table), or the autovacuum GUC variables. |
| 3013 |
*/ |
| 3014 |
|
| 3015 |
/* -1 in autovac setting means use plain vacuum_scale_factor */ |
| 3016 |
vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0) |
| 3017 |
? relopts->vacuum_scale_factor |
| 3018 |
: autovacuum_vac_scale; |
| 3019 |
|
| 3020 |
vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0) |
| 3021 |
? relopts->vacuum_threshold |
| 3022 |
: autovacuum_vac_thresh; |
| 3023 |
|
| 3024 |
/* -1 is used to disable max threshold */ |
| 3025 |
vac_max_thresh = (relopts && relopts->vacuum_max_threshold >= -1) |
| 3026 |
? relopts->vacuum_max_threshold |
| 3027 |
: autovacuum_vac_max_thresh; |
| 3028 |
|
| 3029 |
vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0) |
| 3030 |
? relopts->vacuum_ins_scale_factor |
| 3031 |
: autovacuum_vac_ins_scale; |
| 3032 |
|
| 3033 |
/* -1 is used to disable insert vacuums */ |
| 3034 |
vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1) |
| 3035 |
? relopts->vacuum_ins_threshold |
| 3036 |
: autovacuum_vac_ins_thresh; |
| 3037 |
|
| 3038 |
anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0) |
| 3039 |
? relopts->analyze_scale_factor |
| 3040 |
: autovacuum_anl_scale; |
| 3041 |
|
| 3042 |
anl_base_thresh = (relopts && relopts->analyze_threshold >= 0) |
| 3043 |
? relopts->analyze_threshold |
| 3044 |
: autovacuum_anl_thresh; |
| 3045 |
|
| 3046 |
freeze_max_age = (relopts && relopts->freeze_max_age >= 0) |
| 3047 |
? Min(relopts->freeze_max_age, autovacuum_freeze_max_age) |
| 3048 |
: autovacuum_freeze_max_age; |
| 3049 |
|
| 3050 |
multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0) |
| 3051 |
? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age) |
| 3052 |
: effective_multixact_freeze_max_age; |
| 3053 |
|
| 3054 |
av_enabled = (relopts ? relopts->enabled : true); |
| 3055 |
|
| 3056 |
/* Force vacuum if table is at risk of wraparound */ |
| 3057 |
xidForceLimit = recentXid - freeze_max_age; |
| 3058 |
if (xidForceLimit < FirstNormalTransactionId) |
| 3059 |
xidForceLimit -= FirstNormalTransactionId; |
| 3060 |
relfrozenxid = classForm->relfrozenxid; |
| 3061 |
force_vacuum = (TransactionIdIsNormal(relfrozenxid) && |
| 3062 |
TransactionIdPrecedes(relfrozenxid, xidForceLimit)); |
| 3063 |
if (!force_vacuum) |
| 3064 |
{ |
| 3065 |
MultiXactId relminmxid = classForm->relminmxid; |
| 3066 |
|
| 3067 |
multiForceLimit = recentMulti - multixact_freeze_max_age; |
| 3068 |
if (multiForceLimit < FirstMultiXactId) |
| 3069 |
multiForceLimit -= FirstMultiXactId; |
| 3070 |
force_vacuum = MultiXactIdIsValid(relminmxid) && |
| 3071 |
MultiXactIdPrecedes(relminmxid, multiForceLimit); |
| 3072 |
} |
| 3073 |
*wraparound = force_vacuum; |
| 3074 |
|
| 3075 |
/* User disabled it in pg_class.reloptions? (But ignore if at risk) */ |
| 3076 |
if (!av_enabled && !force_vacuum) |
| 3077 |
{ |
| 3078 |
*doanalyze = false; |
| 3079 |
*dovacuum = false; |
| 3080 |
return; |
| 3081 |
} |
| 3082 |
|
| 3083 |
/* |
| 3084 |
* If we found stats for the table, and autovacuum is currently enabled, |
| 3085 |
* make a threshold-based decision whether to vacuum and/or analyze. If |
| 3086 |
* autovacuum is currently disabled, we must be here for anti-wraparound |
| 3087 |
* vacuuming only, so don't vacuum (or analyze) anything that's not being |
| 3088 |
* forced. |
| 3089 |
*/ |
| 3090 |
if (PointerIsValid(tabentry) && AutoVacuumingActive()) |
| 3091 |
{ |
| 3092 |
float4 pcnt_unfrozen = 1; |
| 3093 |
float4 reltuples = classForm->reltuples; |
| 3094 |
int32 relpages = classForm->relpages; |
| 3095 |
int32 relallfrozen = classForm->relallfrozen; |
| 3096 |
|
| 3097 |
vactuples = tabentry->dead_tuples; |
| 3098 |
instuples = tabentry->ins_since_vacuum; |
| 3099 |
anltuples = tabentry->mod_since_analyze; |
| 3100 |
|
| 3101 |
/* If the table hasn't yet been vacuumed, take reltuples as zero */ |
| 3102 |
if (reltuples < 0) |
| 3103 |
reltuples = 0; |
| 3104 |
|
| 3105 |
/* |
| 3106 |
* If we have data for relallfrozen, calculate the unfrozen percentage |
| 3107 |
* of the table to modify insert scale factor. This helps us decide |
| 3108 |
* whether or not to vacuum an insert-heavy table based on the number |
| 3109 |
* of inserts to the more "active" part of the table. |
| 3110 |
*/ |
| 3111 |
if (relpages > 0 && relallfrozen > 0) |
| 3112 |
{ |
| 3113 |
/* |
| 3114 |
* It could be the stats were updated manually and relallfrozen > |
| 3115 |
* relpages. Clamp relallfrozen to relpages to avoid nonsensical |
| 3116 |
* calculations. |
| 3117 |
*/ |
| 3118 |
relallfrozen = Min(relallfrozen, relpages); |
| 3119 |
pcnt_unfrozen = 1 - ((float4) relallfrozen / relpages); |
| 3120 |
} |
| 3121 |
|
| 3122 |
vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples; |
| 3123 |
if (vac_max_thresh >= 0 && vacthresh > (float4) vac_max_thresh) |
| 3124 |
vacthresh = (float4) vac_max_thresh; |
| 3125 |
|
| 3126 |
vacinsthresh = (float4) vac_ins_base_thresh + |
| 3127 |
vac_ins_scale_factor * reltuples * pcnt_unfrozen; |
| 3128 |
anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples; |
| 3129 |
|
| 3130 |
/* |
| 3131 |
* Note that we don't need to take special consideration for stat |
| 3132 |
* reset, because if that happens, the last vacuum and analyze counts |
| 3133 |
* will be reset too. |
| 3134 |
*/ |
| 3135 |
if (vac_ins_base_thresh >= 0) |
| 3136 |
elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)", |
| 3137 |
NameStr(classForm->relname), |
| 3138 |
vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh); |
| 3139 |
else |
| 3140 |
elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)", |
| 3141 |
NameStr(classForm->relname), |
| 3142 |
vactuples, vacthresh, anltuples, anlthresh); |
| 3143 |
|
| 3144 |
/* Determine if this table needs vacuum or analyze. */ |
| 3145 |
*dovacuum = force_vacuum || (vactuples > vacthresh) || |
| 3146 |
(vac_ins_base_thresh >= 0 && instuples > vacinsthresh); |
| 3147 |
*doanalyze = (anltuples > anlthresh); |
| 3148 |
} |
| 3149 |
else |
| 3150 |
{ |
| 3151 |
/* |
| 3152 |
* Skip a table not found in stat hash, unless we have to force vacuum |
| 3153 |
* for anti-wrap purposes. If it's not acted upon, there's no need to |
| 3154 |
* vacuum it. |
| 3155 |
*/ |
| 3156 |
*dovacuum = force_vacuum; |
| 3157 |
*doanalyze = false; |
| 3158 |
} |
| 3159 |
|
| 3160 |
/* ANALYZE refuses to work with pg_statistic */ |
| 3161 |
if (relid == StatisticRelationId) |
| 3162 |
*doanalyze = false; |
| 3163 |
} |
| 3164 |
|
| 3165 |
/* |
| 3166 |
* autovacuum_do_vac_analyze |
| 3167 |
* Vacuum and/or analyze the specified table |
| 3168 |
* |
| 3169 |
* We expect the caller to have switched into a memory context that won't |
| 3170 |
* disappear at transaction commit. |
| 3171 |
*/ |
| 3172 |
static void |
| 3173 |
autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy) |
| 3174 |
{ |
| 3175 |
RangeVar *rangevar; |
| 3176 |
VacuumRelation *rel; |
| 3177 |
List *rel_list; |
| 3178 |
MemoryContext vac_context; |
| 3179 |
MemoryContext old_context; |
| 3180 |
|
| 3181 |
/* Let pgstat know what we're doing */ |
| 3182 |
autovac_report_activity(tab); |
| 3183 |
|
| 3184 |
/* Create a context that vacuum() can use as cross-transaction storage */ |
| 3185 |
vac_context = AllocSetContextCreate(CurrentMemoryContext, |
| 3186 |
"Vacuum", |
| 3187 |
ALLOCSET_DEFAULT_SIZES); |
| 3188 |
|
| 3189 |
/* Set up one VacuumRelation target, identified by OID, for vacuum() */ |
| 3190 |
old_context = MemoryContextSwitchTo(vac_context); |
| 3191 |
rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1); |
| 3192 |
rel = makeVacuumRelation(rangevar, tab->at_relid, NIL); |
| 3193 |
rel_list = list_make1(rel); |
| 3194 |
MemoryContextSwitchTo(old_context); |
| 3195 |
|
| 3196 |
vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true); |
| 3197 |
|
| 3198 |
MemoryContextDelete(vac_context); |
| 3199 |
} |
| 3200 |
|
| 3201 |
/* |
| 3202 |
* autovac_report_activity |
| 3203 |
* Report to pgstat what autovacuum is doing |
| 3204 |
* |
| 3205 |
* We send a SQL string corresponding to what the user would see if the |
| 3206 |
* equivalent command was to be issued manually. |
| 3207 |
* |
| 3208 |
* Note we assume that we are going to report the next command as soon as we're |
| 3209 |
* done with the current one, and exit right after the last one, so we don't |
| 3210 |
* bother to report "<IDLE>" or some such. |
| 3211 |
*/ |
| 3212 |
static void |
| 3213 |
autovac_report_activity(autovac_table *tab) |
| 3214 |
{ |
| 3215 |
#define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56) |
| 3216 |
char activity[MAX_AUTOVAC_ACTIV_LEN]; |
| 3217 |
int len; |
| 3218 |
|
| 3219 |
/* Report the command and possible options */ |
| 3220 |
if (tab->at_params.options & VACOPT_VACUUM) |
| 3221 |
snprintf(activity, MAX_AUTOVAC_ACTIV_LEN, |
| 3222 |
"autovacuum: VACUUM%s", |
| 3223 |
tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : ""); |
| 3224 |
else |
| 3225 |
snprintf(activity, MAX_AUTOVAC_ACTIV_LEN, |
| 3226 |
"autovacuum: ANALYZE"); |
| 3227 |
|
| 3228 |
/* |
| 3229 |
* Report the qualified name of the relation. |
| 3230 |
*/ |
| 3231 |
len = strlen(activity); |
| 3232 |
|
| 3233 |
snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len, |
| 3234 |
" %s.%s%s", tab->at_nspname, tab->at_relname, |
| 3235 |
tab->at_params.is_wraparound ? " (to prevent wraparound)" : ""); |
| 3236 |
|
| 3237 |
/* Set statement_timestamp() to current time for pg_stat_activity */ |
| 3238 |
SetCurrentStatementStartTimestamp(); |
| 3239 |
|
| 3240 |
pgstat_report_activity(STATE_RUNNING, activity); |
| 3241 |
} |
| 3242 |
|
| 3243 |
/* |
| 3244 |
* autovac_report_workitem |
| 3245 |
* Report to pgstat that autovacuum is processing a work item |
| 3246 |
*/ |
| 3247 |
static void |
| 3248 |
autovac_report_workitem(AutoVacuumWorkItem *workitem, |
| 3249 |
const char *nspname, const char *relname) |
| 3250 |
{ |
| 3251 |
char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2]; |
| 3252 |
char blk[12 + 2]; |
| 3253 |
int len; |
| 3254 |
|
| 3255 |
switch (workitem->avw_type) |
| 3256 |
{ |
| 3257 |
case AVW_BRINSummarizeRange: |
| 3258 |
snprintf(activity, MAX_AUTOVAC_ACTIV_LEN, |
| 3259 |
"autovacuum: BRIN summarize"); |
| 3260 |
break; |
| 3261 |
} |
| 3262 |
|
| 3263 |
/* |
| 3264 |
* Report the qualified name of the relation, and the block number if any |
| 3265 |
*/ |
| 3266 |
len = strlen(activity); |
| 3267 |
|
| 3268 |
if (BlockNumberIsValid(workitem->avw_blockNumber)) |
| 3269 |
snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber); |
| 3270 |
else |
| 3271 |
blk[0] = '\0'; |
| 3272 |
|
| 3273 |
snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len, |
| 3274 |
" %s.%s%s", nspname, relname, blk); |
| 3275 |
|
| 3276 |
/* Set statement_timestamp() to current time for pg_stat_activity */ |
| 3277 |
SetCurrentStatementStartTimestamp(); |
| 3278 |
|
| 3279 |
pgstat_report_activity(STATE_RUNNING, activity); |
| 3280 |
} |
| 3281 |
|
| 3282 |
/* |
| 3283 |
* AutoVacuumingActive |
| 3284 |
* Check GUC vars and report whether the autovacuum process should be |
| 3285 |
* running. |
| 3286 |
*/ |
| 3287 |
bool |
| 3288 |
AutoVacuumingActive(void) |
| 3289 |
{ |
| 3290 |
if (!autovacuum_start_daemon || !pgstat_track_counts) |
| 3291 |
return false; |
| 3292 |
return true; |
| 3293 |
} |
| 3294 |
|
| 3295 |
/* |
| 3296 |
* Request one work item to the next autovacuum run processing our database. |
| 3297 |
* Return false if the request can't be recorded. |
| 3298 |
*/ |
| 3299 |
bool |
| 3300 |
AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId, |
| 3301 |
BlockNumber blkno) |
| 3302 |
{ |
| 3303 |
int i; |
| 3304 |
bool result = false; |
| 3305 |
|
| 3306 |
LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE); |
| 3307 |
|
| 3308 |
/* |
| 3309 |
* Locate an unused work item and fill it with the given data. |
| 3310 |
*/ |
| 3311 |
for (i = 0; i < NUM_WORKITEMS; i++) |
| 3312 |
{ |
| 3313 |
AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i]; |
| 3314 |
|
| 3315 |
if (workitem->avw_used) |
| 3316 |
continue; |
| 3317 |
|
| 3318 |
workitem->avw_used = true; |
| 3319 |
workitem->avw_active = false; |
| 3320 |
workitem->avw_type = type; |
| 3321 |
workitem->avw_database = MyDatabaseId; |
| 3322 |
workitem->avw_relation = relationId; |
| 3323 |
workitem->avw_blockNumber = blkno; |
| 3324 |
result = true; |
| 3325 |
|
| 3326 |
/* done */ |
| 3327 |
break; |
| 3328 |
} |
| 3329 |
|
| 3330 |
LWLockRelease(AutovacuumLock); |
| 3331 |
|
| 3332 |
return result; |
| 3333 |
} |
| 3334 |
|
| 3335 |
/* |
| 3336 |
* autovac_init |
| 3337 |
* This is called at postmaster initialization. |
| 3338 |
* |
| 3339 |
* All we do here is annoy the user if he got it wrong. |
| 3340 |
*/ |
| 3341 |
void |
| 3342 |
autovac_init(void) |
| 3343 |
{ |
| 3344 |
if (!autovacuum_start_daemon) |
| 3345 |
return; |
| 3346 |
else if (!pgstat_track_counts) |
| 3347 |
ereport(WARNING, |
| 3348 |
(errmsg("autovacuum not started because of misconfiguration"), |
| 3349 |
errhint("Enable the \"track_counts\" option."))); |
| 3350 |
else |
| 3351 |
check_av_worker_gucs(); |
| 3352 |
} |
| 3353 |
|
| 3354 |
/* |
| 3355 |
* AutoVacuumShmemSize |
| 3356 |
* Compute space needed for autovacuum-related shared memory |
| 3357 |
*/ |
| 3358 |
Size |
| 3359 |
AutoVacuumShmemSize(void) |
| 3360 |
{ |
| 3361 |
Size size; |
| 3362 |
|
| 3363 |
/* |
| 3364 |
* Need the fixed struct and the array of WorkerInfoData. |
| 3365 |
*/ |
| 3366 |
size = sizeof(AutoVacuumShmemStruct); |
| 3367 |
size = MAXALIGN(size); |
| 3368 |
size = add_size(size, mul_size(autovacuum_worker_slots, |
| 3369 |
sizeof(WorkerInfoData))); |
| 3370 |
return size; |
| 3371 |
} |
| 3372 |
|
| 3373 |
/* |
| 3374 |
* AutoVacuumShmemInit |
| 3375 |
* Allocate and initialize autovacuum-related shared memory |
| 3376 |
*/ |
| 3377 |
void |
| 3378 |
AutoVacuumShmemInit(void) |
| 3379 |
{ |
| 3380 |
bool found; |
| 3381 |
|
| 3382 |
AutoVacuumShmem = (AutoVacuumShmemStruct *) |
| 3383 |
ShmemInitStruct("AutoVacuum Data", |
| 3384 |
AutoVacuumShmemSize(), |
| 3385 |
&found); |
| 3386 |
|
| 3387 |
if (!IsUnderPostmaster) |
| 3388 |
{ |
| 3389 |
WorkerInfo worker; |
| 3390 |
int i; |
| 3391 |
|
| 3392 |
Assert(!found); |
| 3393 |
|
| 3394 |
AutoVacuumShmem->av_launcherpid = 0; |
| 3395 |
dclist_init(&AutoVacuumShmem->av_freeWorkers); |
| 3396 |
dlist_init(&AutoVacuumShmem->av_runningWorkers); |
| 3397 |
AutoVacuumShmem->av_startingWorker = NULL; |
| 3398 |
memset(AutoVacuumShmem->av_workItems, 0, |
| 3399 |
sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS); |
| 3400 |
|
| 3401 |
worker = (WorkerInfo) ((char *) AutoVacuumShmem + |
| 3402 |
MAXALIGN(sizeof(AutoVacuumShmemStruct))); |
| 3403 |
|
| 3404 |
/* initialize the WorkerInfo free list */ |
| 3405 |
for (i = 0; i < autovacuum_worker_slots; i++) |
| 3406 |
{ |
| 3407 |
dclist_push_head(&AutoVacuumShmem->av_freeWorkers, |
| 3408 |
&worker[i].wi_links); |
| 3409 |
pg_atomic_init_flag(&worker[i].wi_dobalance); |
| 3410 |
} |
| 3411 |
|
| 3412 |
pg_atomic_init_u32(&AutoVacuumShmem->av_nworkersForBalance, 0); |
| 3413 |
|
| 3414 |
} |
| 3415 |
else |
| 3416 |
Assert(found); |
| 3417 |
} |
| 3418 |
|
| 3419 |
/* |
| 3420 |
* GUC check_hook for autovacuum_work_mem |
| 3421 |
*/ |
| 3422 |
bool |
| 3423 |
check_autovacuum_work_mem(int *newval, void **extra, GucSource source) |
| 3424 |
{ |
| 3425 |
/* |
| 3426 |
* -1 indicates fallback. |
| 3427 |
* |
| 3428 |
* If we haven't yet changed the boot_val default of -1, just let it be. |
| 3429 |
* Autovacuum will look to maintenance_work_mem instead. |
| 3430 |
*/ |
| 3431 |
if (*newval == -1) |
| 3432 |
return true; |
| 3433 |
|
| 3434 |
/* |
| 3435 |
* We clamp manually-set values to at least 64kB. Since |
| 3436 |
* maintenance_work_mem is always set to at least this value, do the same |
| 3437 |
* here. |
| 3438 |
*/ |
| 3439 |
if (*newval < 64) |
| 3440 |
*newval = 64; |
| 3441 |
|
| 3442 |
return true; |
| 3443 |
} |
| 3444 |
|
| 3445 |
/* |
| 3446 |
* Returns whether there is a free autovacuum worker slot available. |
| 3447 |
*/ |
| 3448 |
static bool |
| 3449 |
av_worker_available(void) |
| 3450 |
{ |
| 3451 |
int free_slots; |
| 3452 |
int reserved_slots; |
| 3453 |
|
| 3454 |
free_slots = dclist_count(&AutoVacuumShmem->av_freeWorkers); |
| 3455 |
|
| 3456 |
reserved_slots = autovacuum_worker_slots - autovacuum_max_workers; |
| 3457 |
reserved_slots = Max(0, reserved_slots); |
| 3458 |
|
| 3459 |
return free_slots > reserved_slots; |
| 3460 |
} |
| 3461 |
|
| 3462 |
/* |
| 3463 |
* Emits a WARNING if autovacuum_worker_slots < autovacuum_max_workers. |
| 3464 |
*/ |
| 3465 |
static void |
| 3466 |
check_av_worker_gucs(void) |
| 3467 |
{ |
| 3468 |
if (autovacuum_worker_slots < autovacuum_max_workers) |
| 3469 |
ereport(WARNING, |
| 3470 |
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), |
| 3471 |
errmsg("\"autovacuum_max_workers\" (%d) should be less than or equal to \"autovacuum_worker_slots\" (%d)", |
| 3472 |
autovacuum_max_workers, autovacuum_worker_slots), |
| 3473 |
errdetail("The server will only start up to \"autovacuum_worker_slots\" (%d) autovacuum workers at a given time.", |
| 3474 |
autovacuum_worker_slots))); |
| 3475 |
} |