Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
miscadmin.h508 linesDownload Raw Back to server
1/*-------------------------------------------------------------------------2 *3 * miscadmin.h4 *	  This file contains general postgres administration and initialization5 *	  stuff that used to be spread out between the following files:6 *		globals.h						global variables7 *		pdir.h							directory path crud8 *		pinit.h							postgres initialization9 *		pmod.h							processing modes10 *	  Over time, this has also become the preferred place for widely known11 *	  resource-limitation stuff, such as work_mem and check_stack_depth().12 *13 * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group14 * Portions Copyright (c) 1994, Regents of the University of California15 *16 * src/include/miscadmin.h17 *18 * NOTES19 *	  some of the information in this file should be moved to other files.20 *21 *-------------------------------------------------------------------------22 */23#ifndef MISCADMIN_H24#define MISCADMIN_H25 26#include <signal.h>27 28#include "datatype/timestamp.h" /* for TimestampTz */29#include "pgtime.h"				/* for pg_time_t */30 31 32#define InvalidPid				(-1)33 34 35/*****************************************************************************36 *	  System interrupt and critical section handling37 *38 * There are two types of interrupts that a running backend needs to accept39 * without messing up its state: QueryCancel (SIGINT) and ProcDie (SIGTERM).40 * In both cases, we need to be able to clean up the current transaction41 * gracefully, so we can't respond to the interrupt instantaneously ---42 * there's no guarantee that internal data structures would be self-consistent43 * if the code is interrupted at an arbitrary instant.  Instead, the signal44 * handlers set flags that are checked periodically during execution.45 *46 * The CHECK_FOR_INTERRUPTS() macro is called at strategically located spots47 * where it is normally safe to accept a cancel or die interrupt.  In some48 * cases, we invoke CHECK_FOR_INTERRUPTS() inside low-level subroutines that49 * might sometimes be called in contexts that do *not* want to allow a cancel50 * or die interrupt.  The HOLD_INTERRUPTS() and RESUME_INTERRUPTS() macros51 * allow code to ensure that no cancel or die interrupt will be accepted,52 * even if CHECK_FOR_INTERRUPTS() gets called in a subroutine.  The interrupt53 * will be held off until CHECK_FOR_INTERRUPTS() is done outside any54 * HOLD_INTERRUPTS() ... RESUME_INTERRUPTS() section.55 *56 * There is also a mechanism to prevent query cancel interrupts, while still57 * allowing die interrupts: HOLD_CANCEL_INTERRUPTS() and58 * RESUME_CANCEL_INTERRUPTS().59 *60 * Note that ProcessInterrupts() has also acquired a number of tasks that61 * do not necessarily cause a query-cancel-or-die response.  Hence, it's62 * possible that it will just clear InterruptPending and return.63 *64 * INTERRUPTS_PENDING_CONDITION() can be checked to see whether an65 * interrupt needs to be serviced, without trying to do so immediately.66 * Some callers are also interested in INTERRUPTS_CAN_BE_PROCESSED(),67 * which tells whether ProcessInterrupts is sure to clear the interrupt.68 *69 * Special mechanisms are used to let an interrupt be accepted when we are70 * waiting for a lock or when we are waiting for command input (but, of71 * course, only if the interrupt holdoff counter is zero).  See the72 * related code for details.73 *74 * A lost connection is handled similarly, although the loss of connection75 * does not raise a signal, but is detected when we fail to write to the76 * socket. If there was a signal for a broken connection, we could make use of77 * it by setting ClientConnectionLost in the signal handler.78 *79 * A related, but conceptually distinct, mechanism is the "critical section"80 * mechanism.  A critical section not only holds off cancel/die interrupts,81 * but causes any ereport(ERROR) or ereport(FATAL) to become ereport(PANIC)82 * --- that is, a system-wide reset is forced.  Needless to say, only really83 * *critical* code should be marked as a critical section!	Currently, this84 * mechanism is only used for XLOG-related code.85 *86 *****************************************************************************/87 88/* in globals.c */89/* these are marked volatile because they are set by signal handlers: */90extern PGDLLIMPORT volatile sig_atomic_t InterruptPending;91extern PGDLLIMPORT volatile sig_atomic_t QueryCancelPending;92extern PGDLLIMPORT volatile sig_atomic_t ProcDiePending;93extern PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending;94extern PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending;95extern PGDLLIMPORT volatile sig_atomic_t ProcSignalBarrierPending;96extern PGDLLIMPORT volatile sig_atomic_t LogMemoryContextPending;97extern PGDLLIMPORT volatile sig_atomic_t IdleStatsUpdateTimeoutPending;98 99extern PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending;100extern PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost;101 102/* these are marked volatile because they are examined by signal handlers: */103extern PGDLLIMPORT volatile uint32 InterruptHoldoffCount;104extern PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount;105extern PGDLLIMPORT volatile uint32 CritSectionCount;106 107/* in tcop/postgres.c */108extern void ProcessInterrupts(void);109 110/* Test whether an interrupt is pending */111#ifndef WIN32112#define INTERRUPTS_PENDING_CONDITION() \113	(unlikely(InterruptPending))114#else115#define INTERRUPTS_PENDING_CONDITION() \116	(unlikely(UNBLOCKED_SIGNAL_QUEUE()) ? pgwin32_dispatch_queued_signals() : 0, \117	 unlikely(InterruptPending))118#endif119 120/* Service interrupt, if one is pending and it's safe to service it now */121#define CHECK_FOR_INTERRUPTS() \122do { \123	if (INTERRUPTS_PENDING_CONDITION()) \124		ProcessInterrupts(); \125} while(0)126 127/* Is ProcessInterrupts() guaranteed to clear InterruptPending? */128#define INTERRUPTS_CAN_BE_PROCESSED() \129	(InterruptHoldoffCount == 0 && CritSectionCount == 0 && \130	 QueryCancelHoldoffCount == 0)131 132#define HOLD_INTERRUPTS()  (InterruptHoldoffCount++)133 134#define RESUME_INTERRUPTS() \135do { \136	Assert(InterruptHoldoffCount > 0); \137	InterruptHoldoffCount--; \138} while(0)139 140#define HOLD_CANCEL_INTERRUPTS()  (QueryCancelHoldoffCount++)141 142#define RESUME_CANCEL_INTERRUPTS() \143do { \144	Assert(QueryCancelHoldoffCount > 0); \145	QueryCancelHoldoffCount--; \146} while(0)147 148#define START_CRIT_SECTION()  (CritSectionCount++)149 150#define END_CRIT_SECTION() \151do { \152	Assert(CritSectionCount > 0); \153	CritSectionCount--; \154} while(0)155 156 157/*****************************************************************************158 *	  globals.h --															 *159 *****************************************************************************/160 161/*162 * from utils/init/globals.c163 */164extern PGDLLIMPORT pid_t PostmasterPid;165extern PGDLLIMPORT bool IsPostmasterEnvironment;166extern PGDLLIMPORT bool IsUnderPostmaster;167extern PGDLLIMPORT bool IsBackgroundWorker;168extern PGDLLIMPORT bool IsBinaryUpgrade;169 170extern PGDLLIMPORT bool ExitOnAnyError;171 172extern PGDLLIMPORT char *DataDir;173extern PGDLLIMPORT int data_directory_mode;174 175extern PGDLLIMPORT int NBuffers;176extern PGDLLIMPORT int MaxBackends;177extern PGDLLIMPORT int MaxConnections;178extern PGDLLIMPORT int max_worker_processes;179extern PGDLLIMPORT int max_parallel_workers;180 181extern PGDLLIMPORT int MyProcPid;182extern PGDLLIMPORT pg_time_t MyStartTime;183extern PGDLLIMPORT TimestampTz MyStartTimestamp;184extern PGDLLIMPORT struct Port *MyProcPort;185extern PGDLLIMPORT struct Latch *MyLatch;186extern PGDLLIMPORT int32 MyCancelKey;187extern PGDLLIMPORT int MyPMChildSlot;188 189extern PGDLLIMPORT char OutputFileName[];190extern PGDLLIMPORT char my_exec_path[];191extern PGDLLIMPORT char pkglib_path[];192 193#ifdef EXEC_BACKEND194extern PGDLLIMPORT char postgres_exec_path[];195#endif196 197/*198 * done in storage/backendid.h for now.199 *200 * extern BackendId    MyBackendId;201 */202extern PGDLLIMPORT Oid MyDatabaseId;203 204extern PGDLLIMPORT Oid MyDatabaseTableSpace;205 206/*207 * Date/Time Configuration208 *209 * DateStyle defines the output formatting choice for date/time types:210 *	USE_POSTGRES_DATES specifies traditional Postgres format211 *	USE_ISO_DATES specifies ISO-compliant format212 *	USE_SQL_DATES specifies Oracle/Ingres-compliant format213 *	USE_GERMAN_DATES specifies German-style dd.mm/yyyy214 *215 * DateOrder defines the field order to be assumed when reading an216 * ambiguous date (anything not in YYYY-MM-DD format, with a four-digit217 * year field first, is taken to be ambiguous):218 *	DATEORDER_YMD specifies field order yy-mm-dd219 *	DATEORDER_DMY specifies field order dd-mm-yy ("European" convention)220 *	DATEORDER_MDY specifies field order mm-dd-yy ("US" convention)221 *222 * In the Postgres and SQL DateStyles, DateOrder also selects output field223 * order: day comes before month in DMY style, else month comes before day.224 *225 * The user-visible "DateStyle" run-time parameter subsumes both of these.226 */227 228/* valid DateStyle values */229#define USE_POSTGRES_DATES		0230#define USE_ISO_DATES			1231#define USE_SQL_DATES			2232#define USE_GERMAN_DATES		3233#define USE_XSD_DATES			4234 235/* valid DateOrder values */236#define DATEORDER_YMD			0237#define DATEORDER_DMY			1238#define DATEORDER_MDY			2239 240extern PGDLLIMPORT int DateStyle;241extern PGDLLIMPORT int DateOrder;242 243/*244 * IntervalStyles245 *	 INTSTYLE_POSTGRES			   Like Postgres < 8.4 when DateStyle = 'iso'246 *	 INTSTYLE_POSTGRES_VERBOSE	   Like Postgres < 8.4 when DateStyle != 'iso'247 *	 INTSTYLE_SQL_STANDARD		   SQL standard interval literals248 *	 INTSTYLE_ISO_8601			   ISO-8601-basic formatted intervals249 */250#define INTSTYLE_POSTGRES			0251#define INTSTYLE_POSTGRES_VERBOSE	1252#define INTSTYLE_SQL_STANDARD		2253#define INTSTYLE_ISO_8601			3254 255extern PGDLLIMPORT int IntervalStyle;256 257#define MAXTZLEN		10		/* max TZ name len, not counting tr. null */258 259extern PGDLLIMPORT bool enableFsync;260extern PGDLLIMPORT bool allowSystemTableMods;261extern PGDLLIMPORT int work_mem;262extern PGDLLIMPORT double hash_mem_multiplier;263extern PGDLLIMPORT int maintenance_work_mem;264extern PGDLLIMPORT int max_parallel_maintenance_workers;265 266/*267 * Upper and lower hard limits for the buffer access strategy ring size268 * specified by the VacuumBufferUsageLimit GUC and BUFFER_USAGE_LIMIT option269 * to VACUUM and ANALYZE.270 */271#define MIN_BAS_VAC_RING_SIZE_KB 128272#define MAX_BAS_VAC_RING_SIZE_KB (16 * 1024 * 1024)273 274extern PGDLLIMPORT int VacuumBufferUsageLimit;275extern PGDLLIMPORT int VacuumCostPageHit;276extern PGDLLIMPORT int VacuumCostPageMiss;277extern PGDLLIMPORT int VacuumCostPageDirty;278extern PGDLLIMPORT int VacuumCostLimit;279extern PGDLLIMPORT double VacuumCostDelay;280 281extern PGDLLIMPORT int64 VacuumPageHit;282extern PGDLLIMPORT int64 VacuumPageMiss;283extern PGDLLIMPORT int64 VacuumPageDirty;284 285extern PGDLLIMPORT int VacuumCostBalance;286extern PGDLLIMPORT bool VacuumCostActive;287 288 289/* in tcop/postgres.c */290 291typedef char *pg_stack_base_t;292 293extern pg_stack_base_t set_stack_base(void);294extern void restore_stack_base(pg_stack_base_t base);295extern void check_stack_depth(void);296extern bool stack_is_too_deep(void);297 298/* in tcop/utility.c */299extern void PreventCommandIfReadOnly(const char *cmdname);300extern void PreventCommandIfParallelMode(const char *cmdname);301extern void PreventCommandDuringRecovery(const char *cmdname);302 303/* in utils/misc/guc_tables.c */304extern PGDLLIMPORT int trace_recovery_messages;305extern int	trace_recovery(int trace_level);306 307/*****************************************************************************308 *	  pdir.h --																 *309 *			POSTGRES directory path definitions.                             *310 *****************************************************************************/311 312/* flags to be OR'd to form sec_context */313#define SECURITY_LOCAL_USERID_CHANGE	0x0001314#define SECURITY_RESTRICTED_OPERATION	0x0002315#define SECURITY_NOFORCE_RLS			0x0004316 317extern PGDLLIMPORT char *DatabasePath;318 319/* now in utils/init/miscinit.c */320extern void InitPostmasterChild(void);321extern void InitStandaloneProcess(const char *argv0);322extern void InitProcessLocalLatch(void);323extern void SwitchToSharedLatch(void);324extern void SwitchBackToLocalLatch(void);325 326typedef enum BackendType327{328	B_INVALID = 0,329	B_ARCHIVER,330	B_AUTOVAC_LAUNCHER,331	B_AUTOVAC_WORKER,332	B_BACKEND,333	B_BG_WORKER,334	B_BG_WRITER,335	B_CHECKPOINTER,336	B_LOGGER,337	B_STANDALONE_BACKEND,338	B_STARTUP,339	B_WAL_RECEIVER,340	B_WAL_SENDER,341	B_WAL_WRITER,342} BackendType;343 344#define BACKEND_NUM_TYPES (B_WAL_WRITER + 1)345 346extern PGDLLIMPORT BackendType MyBackendType;347 348extern const char *GetBackendTypeDesc(BackendType backendType);349 350extern void SetDatabasePath(const char *path);351extern void checkDataDir(void);352extern void SetDataDir(const char *dir);353extern void ChangeToDataDir(void);354 355extern char *GetUserNameFromId(Oid roleid, bool noerr);356extern Oid	GetUserId(void);357extern Oid	GetOuterUserId(void);358extern Oid	GetSessionUserId(void);359extern Oid	GetAuthenticatedUserId(void);360extern void GetUserIdAndSecContext(Oid *userid, int *sec_context);361extern void SetUserIdAndSecContext(Oid userid, int sec_context);362extern bool InLocalUserIdChange(void);363extern bool InSecurityRestrictedOperation(void);364extern bool InNoForceRLSOperation(void);365extern void GetUserIdAndContext(Oid *userid, bool *sec_def_context);366extern void SetUserIdAndContext(Oid userid, bool sec_def_context);367extern void InitializeSessionUserId(const char *rolename, Oid roleid);368extern void InitializeSessionUserIdStandalone(void);369extern void SetSessionAuthorization(Oid userid, bool is_superuser);370extern Oid	GetCurrentRoleId(void);371extern void SetCurrentRoleId(Oid roleid, bool is_superuser);372extern void InitializeSystemUser(const char *authn_id,373								 const char *auth_method);374extern const char *GetSystemUser(void);375 376/* in utils/misc/superuser.c */377extern bool superuser(void);	/* current user is superuser */378extern bool superuser_arg(Oid roleid);	/* given user is superuser */379 380 381/*****************************************************************************382 *	  pmod.h --																 *383 *			POSTGRES processing mode definitions.                            *384 *****************************************************************************/385 386/*387 * Description:388 *		There are three processing modes in POSTGRES.  They are389 * BootstrapProcessing or "bootstrap," InitProcessing or390 * "initialization," and NormalProcessing or "normal."391 *392 * The first two processing modes are used during special times. When the393 * system state indicates bootstrap processing, transactions are all given394 * transaction id "one" and are consequently guaranteed to commit. This mode395 * is used during the initial generation of template databases.396 *397 * Initialization mode: used while starting a backend, until all normal398 * initialization is complete.  Some code behaves differently when executed399 * in this mode to enable system bootstrapping.400 *401 * If a POSTGRES backend process is in normal mode, then all code may be402 * executed normally.403 */404 405typedef enum ProcessingMode406{407	BootstrapProcessing,		/* bootstrap creation of template database */408	InitProcessing,				/* initializing system */409	NormalProcessing			/* normal processing */410} ProcessingMode;411 412extern PGDLLIMPORT ProcessingMode Mode;413 414#define IsBootstrapProcessingMode() (Mode == BootstrapProcessing)415#define IsInitProcessingMode()		(Mode == InitProcessing)416#define IsNormalProcessingMode()	(Mode == NormalProcessing)417 418#define GetProcessingMode() Mode419 420#define SetProcessingMode(mode) \421	do { \422		Assert((mode) == BootstrapProcessing || \423				  (mode) == InitProcessing || \424				  (mode) == NormalProcessing); \425		Mode = (mode); \426	} while(0)427 428 429/*430 * Auxiliary-process type identifiers.  These used to be in bootstrap.h431 * but it seems saner to have them here, with the ProcessingMode stuff.432 * The MyAuxProcType global is defined and set in auxprocess.c.433 *434 * Make sure to list in the glossary any items you add here.435 */436 437typedef enum438{439	NotAnAuxProcess = -1,440	StartupProcess = 0,441	BgWriterProcess,442	ArchiverProcess,443	CheckpointerProcess,444	WalWriterProcess,445	WalReceiverProcess,446 447	NUM_AUXPROCTYPES			/* Must be last! */448} AuxProcType;449 450extern PGDLLIMPORT AuxProcType MyAuxProcType;451 452#define AmStartupProcess()			(MyAuxProcType == StartupProcess)453#define AmBackgroundWriterProcess() (MyAuxProcType == BgWriterProcess)454#define AmArchiverProcess()			(MyAuxProcType == ArchiverProcess)455#define AmCheckpointerProcess()		(MyAuxProcType == CheckpointerProcess)456#define AmWalWriterProcess()		(MyAuxProcType == WalWriterProcess)457#define AmWalReceiverProcess()		(MyAuxProcType == WalReceiverProcess)458 459 460/*****************************************************************************461 *	  pinit.h --															 *462 *			POSTGRES initialization and cleanup definitions.                 *463 *****************************************************************************/464 465/* in utils/init/postinit.c */466extern void pg_split_opts(char **argv, int *argcp, const char *optstr);467extern void InitializeMaxBackends(void);468extern void InitPostgres(const char *in_dbname, Oid dboid,469						 const char *username, Oid useroid,470						 bool load_session_libraries,471						 bool override_allow_connections,472						 char *out_dbname);473extern void BaseInit(void);474 475/* in utils/init/miscinit.c */476extern PGDLLIMPORT bool IgnoreSystemIndexes;477extern PGDLLIMPORT bool process_shared_preload_libraries_in_progress;478extern PGDLLIMPORT bool process_shared_preload_libraries_done;479extern PGDLLIMPORT bool process_shmem_requests_in_progress;480extern PGDLLIMPORT char *session_preload_libraries_string;481extern PGDLLIMPORT char *shared_preload_libraries_string;482extern PGDLLIMPORT char *local_preload_libraries_string;483 484extern void CreateDataDirLockFile(bool amPostmaster);485extern void CreateSocketLockFile(const char *socketfile, bool amPostmaster,486								 const char *socketDir);487extern void TouchSocketLockFiles(void);488extern void AddToDataDirLockFile(int target_line, const char *str);489extern bool RecheckDataDirLockFile(void);490extern void ValidatePgVersion(const char *path);491extern void process_shared_preload_libraries(void);492extern void process_session_preload_libraries(void);493extern void process_shmem_requests(void);494extern void pg_bindtextdomain(const char *domain);495extern bool has_rolreplication(Oid roleid);496 497typedef void (*shmem_request_hook_type) (void);498extern PGDLLIMPORT shmem_request_hook_type shmem_request_hook;499 500extern Size EstimateClientConnectionInfoSpace(void);501extern void SerializeClientConnectionInfo(Size maxsize, char *start_address);502extern void RestoreClientConnectionInfo(char *conninfo);503 504/* in executor/nodeHash.c */505extern size_t get_hash_memory_limit(void);506 507#endif							/* MISCADMIN_H */508