]> granicus.if.org Git - postgresql/blob - src/include/miscadmin.h
Allow discovery of whether a dynamic background worker is running.
[postgresql] / src / include / miscadmin.h
1 /*-------------------------------------------------------------------------
2  *
3  * miscadmin.h
4  *        This file contains general postgres administration and initialization
5  *        stuff that used to be spread out between the following files:
6  *              globals.h                                               global variables
7  *              pdir.h                                                  directory path crud
8  *              pinit.h                                                 postgres initialization
9  *              pmod.h                                                  processing modes
10  *        Over time, this has also become the preferred place for widely known
11  *        resource-limitation stuff, such as work_mem and check_stack_depth().
12  *
13  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
14  * Portions Copyright (c) 1994, Regents of the University of California
15  *
16  * src/include/miscadmin.h
17  *
18  * NOTES
19  *        some of the information in this file should be moved to other files.
20  *
21  *-------------------------------------------------------------------------
22  */
23 #ifndef MISCADMIN_H
24 #define MISCADMIN_H
25
26 #include "pgtime.h"                             /* for pg_time_t */
27
28
29 #define PG_BACKEND_VERSIONSTR "postgres (PostgreSQL) " PG_VERSION "\n"
30
31 #define InvalidPid                              (-1)
32
33
34 /*****************************************************************************
35  *        System interrupt and critical section handling
36  *
37  * There are two types of interrupts that a running backend needs to accept
38  * without messing up its state: QueryCancel (SIGINT) and ProcDie (SIGTERM).
39  * In both cases, we need to be able to clean up the current transaction
40  * gracefully, so we can't respond to the interrupt instantaneously ---
41  * there's no guarantee that internal data structures would be self-consistent
42  * if the code is interrupted at an arbitrary instant.  Instead, the signal
43  * handlers set flags that are checked periodically during execution.
44  *
45  * The CHECK_FOR_INTERRUPTS() macro is called at strategically located spots
46  * where it is normally safe to accept a cancel or die interrupt.  In some
47  * cases, we invoke CHECK_FOR_INTERRUPTS() inside low-level subroutines that
48  * might sometimes be called in contexts that do *not* want to allow a cancel
49  * or die interrupt.  The HOLD_INTERRUPTS() and RESUME_INTERRUPTS() macros
50  * allow code to ensure that no cancel or die interrupt will be accepted,
51  * even if CHECK_FOR_INTERRUPTS() gets called in a subroutine.  The interrupt
52  * will be held off until CHECK_FOR_INTERRUPTS() is done outside any
53  * HOLD_INTERRUPTS() ... RESUME_INTERRUPTS() section.
54  *
55  * Special mechanisms are used to let an interrupt be accepted when we are
56  * waiting for a lock or when we are waiting for command input (but, of
57  * course, only if the interrupt holdoff counter is zero).      See the
58  * related code for details.
59  *
60  * A lost connection is handled similarly, although the loss of connection
61  * does not raise a signal, but is detected when we fail to write to the
62  * socket. If there was a signal for a broken connection, we could make use of
63  * it by setting ClientConnectionLost in the signal handler.
64  *
65  * A related, but conceptually distinct, mechanism is the "critical section"
66  * mechanism.  A critical section not only holds off cancel/die interrupts,
67  * but causes any ereport(ERROR) or ereport(FATAL) to become ereport(PANIC)
68  * --- that is, a system-wide reset is forced.  Needless to say, only really
69  * *critical* code should be marked as a critical section!      Currently, this
70  * mechanism is only used for XLOG-related code.
71  *
72  *****************************************************************************/
73
74 /* in globals.c */
75 /* these are marked volatile because they are set by signal handlers: */
76 extern PGDLLIMPORT volatile bool InterruptPending;
77 extern volatile bool QueryCancelPending;
78 extern volatile bool ProcDiePending;
79
80 extern volatile bool ClientConnectionLost;
81
82 /* these are marked volatile because they are examined by signal handlers: */
83 extern volatile bool ImmediateInterruptOK;
84 extern PGDLLIMPORT volatile uint32 InterruptHoldoffCount;
85 extern PGDLLIMPORT volatile uint32 CritSectionCount;
86
87 /* in tcop/postgres.c */
88 extern void ProcessInterrupts(void);
89
90 #ifndef WIN32
91
92 #define CHECK_FOR_INTERRUPTS() \
93 do { \
94         if (InterruptPending) \
95                 ProcessInterrupts(); \
96 } while(0)
97 #else                                                   /* WIN32 */
98
99 #define CHECK_FOR_INTERRUPTS() \
100 do { \
101         if (UNBLOCKED_SIGNAL_QUEUE()) \
102                 pgwin32_dispatch_queued_signals(); \
103         if (InterruptPending) \
104                 ProcessInterrupts(); \
105 } while(0)
106 #endif   /* WIN32 */
107
108
109 #define HOLD_INTERRUPTS()  (InterruptHoldoffCount++)
110
111 #define RESUME_INTERRUPTS() \
112 do { \
113         Assert(InterruptHoldoffCount > 0); \
114         InterruptHoldoffCount--; \
115 } while(0)
116
117 #define START_CRIT_SECTION()  (CritSectionCount++)
118
119 #define END_CRIT_SECTION() \
120 do { \
121         Assert(CritSectionCount > 0); \
122         CritSectionCount--; \
123 } while(0)
124
125
126 /*****************************************************************************
127  *        globals.h --                                                                                                                   *
128  *****************************************************************************/
129
130 /*
131  * from utils/init/globals.c
132  */
133 extern pid_t PostmasterPid;
134 extern bool IsPostmasterEnvironment;
135 extern PGDLLIMPORT bool IsUnderPostmaster;
136 extern bool IsBackgroundWorker;
137 extern bool IsBinaryUpgrade;
138
139 extern bool ExitOnAnyError;
140
141 extern PGDLLIMPORT char *DataDir;
142
143 extern PGDLLIMPORT int NBuffers;
144 extern int      MaxBackends;
145 extern int      MaxConnections;
146 extern int      max_worker_processes;
147
148 extern PGDLLIMPORT int MyProcPid;
149 extern PGDLLIMPORT pg_time_t MyStartTime;
150 extern PGDLLIMPORT struct Port *MyProcPort;
151 extern long MyCancelKey;
152 extern int      MyPMChildSlot;
153
154 extern char OutputFileName[];
155 extern PGDLLIMPORT char my_exec_path[];
156 extern char pkglib_path[];
157
158 #ifdef EXEC_BACKEND
159 extern char postgres_exec_path[];
160 #endif
161
162 /*
163  * done in storage/backendid.h for now.
164  *
165  * extern BackendId    MyBackendId;
166  */
167 extern PGDLLIMPORT Oid MyDatabaseId;
168
169 extern PGDLLIMPORT Oid MyDatabaseTableSpace;
170
171 /*
172  * Date/Time Configuration
173  *
174  * DateStyle defines the output formatting choice for date/time types:
175  *      USE_POSTGRES_DATES specifies traditional Postgres format
176  *      USE_ISO_DATES specifies ISO-compliant format
177  *      USE_SQL_DATES specifies Oracle/Ingres-compliant format
178  *      USE_GERMAN_DATES specifies German-style dd.mm/yyyy
179  *
180  * DateOrder defines the field order to be assumed when reading an
181  * ambiguous date (anything not in YYYY-MM-DD format, with a four-digit
182  * year field first, is taken to be ambiguous):
183  *      DATEORDER_YMD specifies field order yy-mm-dd
184  *      DATEORDER_DMY specifies field order dd-mm-yy ("European" convention)
185  *      DATEORDER_MDY specifies field order mm-dd-yy ("US" convention)
186  *
187  * In the Postgres and SQL DateStyles, DateOrder also selects output field
188  * order: day comes before month in DMY style, else month comes before day.
189  *
190  * The user-visible "DateStyle" run-time parameter subsumes both of these.
191  */
192
193 /* valid DateStyle values */
194 #define USE_POSTGRES_DATES              0
195 #define USE_ISO_DATES                   1
196 #define USE_SQL_DATES                   2
197 #define USE_GERMAN_DATES                3
198 #define USE_XSD_DATES                   4
199
200 /* valid DateOrder values */
201 #define DATEORDER_YMD                   0
202 #define DATEORDER_DMY                   1
203 #define DATEORDER_MDY                   2
204
205 extern int      DateStyle;
206 extern int      DateOrder;
207
208 /*
209  * IntervalStyles
210  *       INTSTYLE_POSTGRES                         Like Postgres < 8.4 when DateStyle = 'iso'
211  *       INTSTYLE_POSTGRES_VERBOSE         Like Postgres < 8.4 when DateStyle != 'iso'
212  *       INTSTYLE_SQL_STANDARD             SQL standard interval literals
213  *       INTSTYLE_ISO_8601                         ISO-8601-basic formatted intervals
214  */
215 #define INTSTYLE_POSTGRES                       0
216 #define INTSTYLE_POSTGRES_VERBOSE       1
217 #define INTSTYLE_SQL_STANDARD           2
218 #define INTSTYLE_ISO_8601                       3
219
220 extern int      IntervalStyle;
221
222 /*
223  * HasCTZSet is true if user has set timezone as a numeric offset from UTC.
224  * If so, CTimeZone is the timezone offset in seconds (using the Unix-ish
225  * sign convention, ie, positive offset is west of UTC, rather than the
226  * SQL-ish convention that positive is east of UTC).
227  */
228 extern bool HasCTZSet;
229 extern int      CTimeZone;
230
231 #define MAXTZLEN                10              /* max TZ name len, not counting tr. null */
232
233 extern bool enableFsync;
234 extern bool allowSystemTableMods;
235 extern PGDLLIMPORT int work_mem;
236 extern PGDLLIMPORT int maintenance_work_mem;
237
238 extern int      VacuumCostPageHit;
239 extern int      VacuumCostPageMiss;
240 extern int      VacuumCostPageDirty;
241 extern int      VacuumCostLimit;
242 extern int      VacuumCostDelay;
243
244 extern int      VacuumPageHit;
245 extern int      VacuumPageMiss;
246 extern int      VacuumPageDirty;
247
248 extern int      VacuumCostBalance;
249 extern bool VacuumCostActive;
250
251
252 /* in tcop/postgres.c */
253
254 #if defined(__ia64__) || defined(__ia64)
255 typedef struct
256 {
257         char       *stack_base_ptr;
258         char       *register_stack_base_ptr;
259 } pg_stack_base_t;
260 #else
261 typedef char *pg_stack_base_t;
262 #endif
263
264 extern pg_stack_base_t set_stack_base(void);
265 extern void restore_stack_base(pg_stack_base_t base);
266 extern void check_stack_depth(void);
267
268 /* in tcop/utility.c */
269 extern void PreventCommandIfReadOnly(const char *cmdname);
270 extern void PreventCommandDuringRecovery(const char *cmdname);
271
272 /* in utils/misc/guc.c */
273 extern int      trace_recovery_messages;
274 extern int      trace_recovery(int trace_level);
275
276 /*****************************************************************************
277  *        pdir.h --                                                                                                                              *
278  *                      POSTGRES directory path definitions.                                                     *
279  *****************************************************************************/
280
281 /* flags to be OR'd to form sec_context */
282 #define SECURITY_LOCAL_USERID_CHANGE    0x0001
283 #define SECURITY_RESTRICTED_OPERATION   0x0002
284
285 extern char *DatabasePath;
286
287 /* now in utils/init/miscinit.c */
288 extern void SetDatabasePath(const char *path);
289
290 extern char *GetUserNameFromId(Oid roleid);
291 extern Oid      GetUserId(void);
292 extern Oid      GetOuterUserId(void);
293 extern Oid      GetSessionUserId(void);
294 extern void GetUserIdAndSecContext(Oid *userid, int *sec_context);
295 extern void SetUserIdAndSecContext(Oid userid, int sec_context);
296 extern bool InLocalUserIdChange(void);
297 extern bool InSecurityRestrictedOperation(void);
298 extern void GetUserIdAndContext(Oid *userid, bool *sec_def_context);
299 extern void SetUserIdAndContext(Oid userid, bool sec_def_context);
300 extern void InitializeSessionUserId(const char *rolename);
301 extern void InitializeSessionUserIdStandalone(void);
302 extern void SetSessionAuthorization(Oid userid, bool is_superuser);
303 extern Oid      GetCurrentRoleId(void);
304 extern void SetCurrentRoleId(Oid roleid, bool is_superuser);
305
306 extern void SetDataDir(const char *dir);
307 extern void ChangeToDataDir(void);
308 extern char *make_absolute_path(const char *path);
309
310 /* in utils/misc/superuser.c */
311 extern bool superuser(void);    /* current user is superuser */
312 extern bool superuser_arg(Oid roleid);  /* given user is superuser */
313
314
315 /*****************************************************************************
316  *        pmod.h --                                                                                                                              *
317  *                      POSTGRES processing mode definitions.                                                    *
318  *****************************************************************************/
319
320 /*
321  * Description:
322  *              There are three processing modes in POSTGRES.  They are
323  * BootstrapProcessing or "bootstrap," InitProcessing or
324  * "initialization," and NormalProcessing or "normal."
325  *
326  * The first two processing modes are used during special times. When the
327  * system state indicates bootstrap processing, transactions are all given
328  * transaction id "one" and are consequently guaranteed to commit. This mode
329  * is used during the initial generation of template databases.
330  *
331  * Initialization mode: used while starting a backend, until all normal
332  * initialization is complete.  Some code behaves differently when executed
333  * in this mode to enable system bootstrapping.
334  *
335  * If a POSTGRES backend process is in normal mode, then all code may be
336  * executed normally.
337  */
338
339 typedef enum ProcessingMode
340 {
341         BootstrapProcessing,            /* bootstrap creation of template database */
342         InitProcessing,                         /* initializing system */
343         NormalProcessing                        /* normal processing */
344 } ProcessingMode;
345
346 extern ProcessingMode Mode;
347
348 #define IsBootstrapProcessingMode() (Mode == BootstrapProcessing)
349 #define IsInitProcessingMode()          (Mode == InitProcessing)
350 #define IsNormalProcessingMode()        (Mode == NormalProcessing)
351
352 #define GetProcessingMode() Mode
353
354 #define SetProcessingMode(mode) \
355         do { \
356                 AssertArg((mode) == BootstrapProcessing || \
357                                   (mode) == InitProcessing || \
358                                   (mode) == NormalProcessing); \
359                 Mode = (mode); \
360         } while(0)
361
362
363 /*
364  * Auxiliary-process type identifiers.  These used to be in bootstrap.h
365  * but it seems saner to have them here, with the ProcessingMode stuff.
366  * The MyAuxProcType global is defined and set in bootstrap.c.
367  */
368
369 typedef enum
370 {
371         NotAnAuxProcess = -1,
372         CheckerProcess = 0,
373         BootstrapProcess,
374         StartupProcess,
375         BgWriterProcess,
376         CheckpointerProcess,
377         WalWriterProcess,
378         WalReceiverProcess,
379
380         NUM_AUXPROCTYPES                        /* Must be last! */
381 } AuxProcType;
382
383 extern AuxProcType MyAuxProcType;
384
385 #define AmBootstrapProcess()            (MyAuxProcType == BootstrapProcess)
386 #define AmStartupProcess()                      (MyAuxProcType == StartupProcess)
387 #define AmBackgroundWriterProcess() (MyAuxProcType == BgWriterProcess)
388 #define AmCheckpointerProcess()         (MyAuxProcType == CheckpointerProcess)
389 #define AmWalWriterProcess()            (MyAuxProcType == WalWriterProcess)
390 #define AmWalReceiverProcess()          (MyAuxProcType == WalReceiverProcess)
391
392
393 /*****************************************************************************
394  *        pinit.h --                                                                                                                     *
395  *                      POSTGRES initialization and cleanup definitions.                                 *
396  *****************************************************************************/
397
398 /* in utils/init/postinit.c */
399 extern void pg_split_opts(char **argv, int *argcp, char *optstr);
400 extern void InitializeMaxBackends(void);
401 extern void InitPostgres(const char *in_dbname, Oid dboid, const char *username,
402                          char *out_dbname);
403 extern void BaseInit(void);
404
405 /* in utils/init/miscinit.c */
406 extern bool IgnoreSystemIndexes;
407 extern PGDLLIMPORT bool process_shared_preload_libraries_in_progress;
408 extern char *session_preload_libraries_string;
409 extern char *shared_preload_libraries_string;
410 extern char *local_preload_libraries_string;
411
412 /*
413  * As of 9.1, the contents of the data-directory lock file are:
414  *
415  * line #
416  *              1       postmaster PID (or negative of a standalone backend's PID)
417  *              2       data directory path
418  *              3       postmaster start timestamp (time_t representation)
419  *              4       port number
420  *              5       first Unix socket directory path (empty if none)
421  *              6       first listen_address (IP address or "*"; empty if no TCP port)
422  *              7       shared memory key (not present on Windows)
423  *
424  * Lines 6 and up are added via AddToDataDirLockFile() after initial file
425  * creation.
426  *
427  * The socket lock file, if used, has the same contents as lines 1-5.
428  */
429 #define LOCK_FILE_LINE_PID                      1
430 #define LOCK_FILE_LINE_DATA_DIR         2
431 #define LOCK_FILE_LINE_START_TIME       3
432 #define LOCK_FILE_LINE_PORT                     4
433 #define LOCK_FILE_LINE_SOCKET_DIR       5
434 #define LOCK_FILE_LINE_LISTEN_ADDR      6
435 #define LOCK_FILE_LINE_SHMEM_KEY        7
436
437 extern void CreateDataDirLockFile(bool amPostmaster);
438 extern void CreateSocketLockFile(const char *socketfile, bool amPostmaster,
439                                          const char *socketDir);
440 extern void TouchSocketLockFiles(void);
441 extern void AddToDataDirLockFile(int target_line, const char *str);
442 extern void ValidatePgVersion(const char *path);
443 extern void process_shared_preload_libraries(void);
444 extern void process_session_preload_libraries(void);
445 extern void pg_bindtextdomain(const char *domain);
446 extern bool has_rolreplication(Oid roleid);
447
448 /* in access/transam/xlog.c */
449 extern bool BackupInProgress(void);
450 extern void CancelBackup(void);
451
452 #endif   /* MISCADMIN_H */