PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
tcopprot.h File Reference
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "nodes/plannodes.h"
#include "storage/procsignal.h"
#include "utils/guc.h"
Include dependency graph for tcopprot.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define STACK_DEPTH_SLOP   (512 * 1024L)
 

Enumerations

enum  LogStmtLevel { LOGSTMT_NONE, LOGSTMT_DDL, LOGSTMT_MOD, LOGSTMT_ALL }
 

Functions

Listpg_parse_query (const char *query_string)
 
Listpg_analyze_and_rewrite (RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams)
 
Listpg_analyze_and_rewrite_params (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg)
 
PlannedStmtpg_plan_query (Query *querytree, int cursorOptions, ParamListInfo boundParams)
 
Listpg_plan_queries (List *querytrees, int cursorOptions, ParamListInfo boundParams)
 
bool check_max_stack_depth (int *newval, void **extra, GucSource source)
 
void assign_max_stack_depth (int newval, void *extra)
 
void die (SIGNAL_ARGS)
 
void quickdie (SIGNAL_ARGS) pg_attribute_noreturn()
 
void StatementCancelHandler (SIGNAL_ARGS)
 
void FloatExceptionHandler (SIGNAL_ARGS) pg_attribute_noreturn()
 
void RecoveryConflictInterrupt (ProcSignalReason reason)
 
void ProcessClientReadInterrupt (bool blocked)
 
void ProcessClientWriteInterrupt (bool blocked)
 
void process_postgres_switches (int argc, char *argv[], GucContext ctx, const char **dbname)
 
void PostgresMain (int argc, char *argv[], const char *dbname, const char *username) pg_attribute_noreturn()
 
long get_stack_depth_rlimit (void)
 
void ResetUsage (void)
 
void ShowUsage (const char *title)
 
int check_log_duration (char *msec_str, bool was_logged)
 
void set_debug_options (int debug_flag, GucContext context, GucSource source)
 
bool set_plan_disabling_options (const char *arg, GucContext context, GucSource source)
 
const char * get_stats_option_name (const char *arg)
 

Variables

CommandDest whereToSendOutput
 
PGDLLIMPORT const char * debug_query_string
 
int max_stack_depth
 
int PostAuthDelay
 
int log_statement
 

Macro Definition Documentation

#define STACK_DEPTH_SLOP   (512 * 1024L)

Definition at line 30 of file tcopprot.h.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

Enumeration Type Documentation

Enumerator
LOGSTMT_NONE 
LOGSTMT_DDL 
LOGSTMT_MOD 
LOGSTMT_ALL 

Definition at line 39 of file tcopprot.h.

40 {
41  LOGSTMT_NONE, /* log no statements */
42  LOGSTMT_DDL, /* log data definition statements */
43  LOGSTMT_MOD, /* log modification statements, plus DDL */
44  LOGSTMT_ALL /* log all statements */
45 } LogStmtLevel;
LogStmtLevel
Definition: tcopprot.h:39

Function Documentation

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3178 of file postgres.c.

References max_stack_depth_bytes.

3179 {
3180  long newval_bytes = newval * 1024L;
3181 
3182  max_stack_depth_bytes = newval_bytes;
3183 }
static long max_stack_depth_bytes
Definition: postgres.c:107
#define newval
int check_log_duration ( char *  msec_str,
bool  was_logged 
)

Definition at line 2102 of file postgres.c.

References GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), log_duration, log_min_duration_statement, snprintf(), and TimestampDifference().

Referenced by exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), and HandleFunctionRequest().

2103 {
2105  {
2106  long secs;
2107  int usecs;
2108  int msecs;
2109  bool exceeded;
2110 
2113  &secs, &usecs);
2114  msecs = usecs / 1000;
2115 
2116  /*
2117  * This odd-looking test for log_min_duration_statement being exceeded
2118  * is designed to avoid integer overflow with very long durations:
2119  * don't compute secs * 1000 until we've verified it will fit in int.
2120  */
2121  exceeded = (log_min_duration_statement == 0 ||
2123  (secs > log_min_duration_statement / 1000 ||
2124  secs * 1000 + msecs >= log_min_duration_statement)));
2125 
2126  if (exceeded || log_duration)
2127  {
2128  snprintf(msec_str, 32, "%ld.%03d",
2129  secs * 1000 + msecs, usecs % 1000);
2130  if (exceeded && !was_logged)
2131  return 2;
2132  else
2133  return 1;
2134  }
2135  }
2136 
2137  return 0;
2138 }
int log_min_duration_statement
Definition: guc.c:456
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
bool log_duration
Definition: guc.c:435
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1623
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:717
bool check_max_stack_depth ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3161 of file postgres.c.

References get_stack_depth_rlimit(), GUC_check_errdetail, GUC_check_errhint, and STACK_DEPTH_SLOP.

3162 {
3163  long newval_bytes = *newval * 1024L;
3164  long stack_rlimit = get_stack_depth_rlimit();
3165 
3166  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3167  {
3168  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3169  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3170  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3171  return false;
3172  }
3173  return true;
3174 }
#define GUC_check_errdetail
Definition: guc.h:407
long get_stack_depth_rlimit(void)
Definition: postgres.c:4345
#define newval
#define GUC_check_errhint
Definition: guc.h:411
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:30
void die ( SIGNAL_ARGS  )

Definition at line 2619 of file postgres.c.

References DestRemote, DoingCommandRead, InterruptPending, MyLatch, proc_exit_inprogress, ProcDiePending, ProcessInterrupts(), SetLatch(), and whereToSendOutput.

Referenced by AutoVacWorkerMain(), bootstrap_signals(), ParallelWorkerMain(), PostgresMain(), and WalSndSignals().

2620 {
2621  int save_errno = errno;
2622 
2623  /* Don't joggle the elbow of proc_exit */
2624  if (!proc_exit_inprogress)
2625  {
2626  InterruptPending = true;
2627  ProcDiePending = true;
2628  }
2629 
2630  /* If we're still here, waken anything waiting on the process latch */
2631  SetLatch(MyLatch);
2632 
2633  /*
2634  * If we're in single user mode, we want to quit immediately - we can't
2635  * rely on latches as they wouldn't work when stdin/stdout is a file.
2636  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2637  * effort just for the benefit of single user mode.
2638  */
2641 
2642  errno = save_errno;
2643 }
void ProcessInterrupts(void)
Definition: postgres.c:2821
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:379
bool proc_exit_inprogress
Definition: ipc.c:40
static bool DoingCommandRead
Definition: postgres.c:142
volatile bool ProcDiePending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:51
CommandDest whereToSendOutput
Definition: postgres.c:86
void FloatExceptionHandler ( SIGNAL_ARGS  )

Definition at line 2671 of file postgres.c.

References ereport, errcode(), errdetail(), errmsg(), and ERROR.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), plperl_init_interp(), PostgresMain(), and StartBackgroundWorker().

2672 {
2673  /* We're not returning, so no need to save errno */
2674  ereport(ERROR,
2675  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2676  errmsg("floating-point exception"),
2677  errdetail("An invalid floating-point operation was signaled. "
2678  "This probably means an out-of-range result or an "
2679  "invalid operation, such as division by zero.")));
2680 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
long get_stack_depth_rlimit ( void  )

Definition at line 4345 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

4346 {
4347 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4348  static long val = 0;
4349 
4350  /* This won't change after process launch, so check just once */
4351  if (val == 0)
4352  {
4353  struct rlimit rlim;
4354 
4355  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4356  val = -1;
4357  else if (rlim.rlim_cur == RLIM_INFINITY)
4358  val = LONG_MAX;
4359  /* rlim_cur is probably of an unsigned type, so check for overflow */
4360  else if (rlim.rlim_cur >= LONG_MAX)
4361  val = LONG_MAX;
4362  else
4363  val = rlim.rlim_cur;
4364  }
4365  return val;
4366 #else /* no getrlimit */
4367 #if defined(WIN32) || defined(__CYGWIN__)
4368  /* On Windows we set the backend stack size in src/backend/Makefile */
4369  return WIN32_STACK_RLIMIT;
4370 #else /* not windows ... give up */
4371  return -1;
4372 #endif
4373 #endif
4374 }
long val
Definition: informix.c:689
const char* get_stats_option_name ( const char *  arg)

Definition at line 3264 of file postgres.c.

References NULL, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3265 {
3266  switch (arg[0])
3267  {
3268  case 'p':
3269  if (optarg[1] == 'a') /* "parser" */
3270  return "log_parser_stats";
3271  else if (optarg[1] == 'l') /* "planner" */
3272  return "log_planner_stats";
3273  break;
3274 
3275  case 'e': /* "executor" */
3276  return "log_executor_stats";
3277  break;
3278  }
3279 
3280  return NULL;
3281 }
#define NULL
Definition: c.h:229
char * optarg
Definition: getopt.c:53
void * arg
List* pg_analyze_and_rewrite ( RawStmt parsetree,
const char *  query_string,
Oid paramTypes,
int  numParams 
)

Definition at line 644 of file postgres.c.

References log_parser_stats, parse_analyze(), pg_rewrite_query(), ResetUsage(), and ShowUsage().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), BeginCopy(), exec_simple_query(), execute_sql_string(), and RevalidateCachedQuery().

646 {
647  Query *query;
648  List *querytree_list;
649 
650  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
651 
652  /*
653  * (1) Perform parse analysis.
654  */
655  if (log_parser_stats)
656  ResetUsage();
657 
658  query = parse_analyze(parsetree, query_string, paramTypes, numParams);
659 
660  if (log_parser_stats)
661  ShowUsage("PARSE ANALYSIS STATISTICS");
662 
663  /*
664  * (2) Rewrite the queries, as necessary
665  */
666  querytree_list = pg_rewrite_query(query);
667 
668  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
669 
670  return querytree_list;
671 }
bool log_parser_stats
Definition: guc.c:441
void ShowUsage(const char *title)
Definition: postgres.c:4388
Query * parse_analyze(RawStmt *parseTree, const char *sourceText, Oid *paramTypes, int numParams)
Definition: analyze.c:96
void ResetUsage(void)
Definition: postgres.c:4381
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:729
Definition: pg_list.h:45
List* pg_analyze_and_rewrite_params ( RawStmt parsetree,
const char *  query_string,
ParserSetupHook  parserSetup,
void *  parserSetupArg 
)

Definition at line 679 of file postgres.c.

References Assert, free_parsestate(), log_parser_stats, make_parsestate(), NULL, ParseState::p_sourcetext, pg_rewrite_query(), post_parse_analyze_hook, ResetUsage(), ShowUsage(), and transformTopLevelStmt().

Referenced by _SPI_execute_plan(), _SPI_prepare_plan(), fmgr_sql_validator(), init_sql_fcache(), inline_set_returning_function(), and RevalidateCachedQuery().

683 {
684  ParseState *pstate;
685  Query *query;
686  List *querytree_list;
687 
688  Assert(query_string != NULL); /* required as of 8.4 */
689 
690  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
691 
692  /*
693  * (1) Perform parse analysis.
694  */
695  if (log_parser_stats)
696  ResetUsage();
697 
698  pstate = make_parsestate(NULL);
699  pstate->p_sourcetext = query_string;
700  (*parserSetup) (pstate, parserSetupArg);
701 
702  query = transformTopLevelStmt(pstate, parsetree);
703 
705  (*post_parse_analyze_hook) (pstate, query);
706 
707  free_parsestate(pstate);
708 
709  if (log_parser_stats)
710  ShowUsage("PARSE ANALYSIS STATISTICS");
711 
712  /*
713  * (2) Rewrite the queries, as necessary
714  */
715  querytree_list = pg_rewrite_query(query);
716 
717  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
718 
719  return querytree_list;
720 }
bool log_parser_stats
Definition: guc.c:441
void ShowUsage(const char *title)
Definition: postgres.c:4388
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4381
const char * p_sourcetext
Definition: parse_node.h:167
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:729
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:184
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:75
Definition: pg_list.h:45
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:49
List* pg_parse_query ( const char *  query_string)

Definition at line 602 of file postgres.c.

References copyObject(), elog, equal(), log_parser_stats, new_list(), raw_parser(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by _SPI_prepare_oneshot_plan(), _SPI_prepare_plan(), exec_parse_message(), exec_simple_query(), execute_sql_string(), fmgr_sql_validator(), ImportForeignSchema(), init_sql_fcache(), inline_function(), and inline_set_returning_function().

603 {
604  List *raw_parsetree_list;
605 
606  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
607 
608  if (log_parser_stats)
609  ResetUsage();
610 
611  raw_parsetree_list = raw_parser(query_string);
612 
613  if (log_parser_stats)
614  ShowUsage("PARSER STATISTICS");
615 
616 #ifdef COPY_PARSE_PLAN_TREES
617  /* Optional debugging check: pass raw parsetrees through copyObject() */
618  {
619  List *new_list = (List *) copyObject(raw_parsetree_list);
620 
621  /* This checks both copyObject() and the equal() routines... */
622  if (!equal(new_list, raw_parsetree_list))
623  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
624  else
625  raw_parsetree_list = new_list;
626  }
627 #endif
628 
629  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
630 
631  return raw_parsetree_list;
632 }
List * raw_parser(const char *str)
Definition: parser.c:36
bool log_parser_stats
Definition: guc.c:441
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2934
void ShowUsage(const char *title)
Definition: postgres.c:4388
static List * new_list(NodeTag type)
Definition: list.c:63
void * copyObject(const void *from)
Definition: copyfuncs.c:4605
void ResetUsage(void)
Definition: postgres.c:4381
#define WARNING
Definition: elog.h:40
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
List* pg_plan_queries ( List querytrees,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 842 of file postgres.c.

References PlannedStmt::canSetTag, Query::canSetTag, castNode, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, lappend(), lfirst, makeNode, NIL, pg_plan_query(), PlannedStmt::stmt_len, Query::stmt_len, PlannedStmt::stmt_location, Query::stmt_location, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by BuildCachedPlan(), exec_simple_query(), and execute_sql_string().

843 {
844  List *stmt_list = NIL;
845  ListCell *query_list;
846 
847  foreach(query_list, querytrees)
848  {
849  Query *query = castNode(Query, lfirst(query_list));
850  PlannedStmt *stmt;
851 
852  if (query->commandType == CMD_UTILITY)
853  {
854  /* Utility commands require no planning. */
855  stmt = makeNode(PlannedStmt);
856  stmt->commandType = CMD_UTILITY;
857  stmt->canSetTag = query->canSetTag;
858  stmt->utilityStmt = query->utilityStmt;
859  stmt->stmt_location = query->stmt_location;
860  stmt->stmt_len = query->stmt_len;
861  }
862  else
863  {
864  stmt = pg_plan_query(query, cursorOptions, boundParams);
865  }
866 
867  stmt_list = lappend(stmt_list, stmt);
868  }
869 
870  return stmt_list;
871 }
#define NIL
Definition: pg_list.h:69
int stmt_location
Definition: parsenodes.h:171
#define castNode(_type_, nodeptr)
Definition: nodes.h:589
Node * utilityStmt
Definition: parsenodes.h:111
int stmt_len
Definition: plannodes.h:87
int stmt_location
Definition: plannodes.h:86
Node * utilityStmt
Definition: plannodes.h:83
List * lappend(List *list, void *datum)
Definition: list.c:128
bool canSetTag
Definition: plannodes.h:53
CmdType commandType
Definition: plannodes.h:45
CmdType commandType
Definition: parsenodes.h:103
#define makeNode(_type_)
Definition: nodes.h:568
#define lfirst(lc)
Definition: pg_list.h:106
bool canSetTag
Definition: parsenodes.h:109
Definition: pg_list.h:45
int stmt_len
Definition: parsenodes.h:172
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:781
PlannedStmt* pg_plan_query ( Query querytree,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 781 of file postgres.c.

References ActiveSnapshotSet(), Assert, CMD_UTILITY, Query::commandType, copyObject(), Debug_pretty_print, Debug_print_plan, elog, elog_node_display(), equal(), LOG, log_planner_stats, NULL, planner(), ResetUsage(), ShowUsage(), and WARNING.

Referenced by BeginCopy(), ExecCreateTableAs(), ExplainOneQuery(), init_execution_state(), PerformCursorOpen(), pg_plan_queries(), and refresh_matview_datafill().

782 {
783  PlannedStmt *plan;
784 
785  /* Utility commands have no plans. */
786  if (querytree->commandType == CMD_UTILITY)
787  return NULL;
788 
789  /* Planner must have a snapshot in case it calls user-defined functions. */
791 
792  TRACE_POSTGRESQL_QUERY_PLAN_START();
793 
794  if (log_planner_stats)
795  ResetUsage();
796 
797  /* call the optimizer */
798  plan = planner(querytree, cursorOptions, boundParams);
799 
800  if (log_planner_stats)
801  ShowUsage("PLANNER STATISTICS");
802 
803 #ifdef COPY_PARSE_PLAN_TREES
804  /* Optional debugging check: pass plan output through copyObject() */
805  {
806  PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
807 
808  /*
809  * equal() currently does not have routines to compare Plan nodes, so
810  * don't try to test equality here. Perhaps fix someday?
811  */
812 #ifdef NOT_USED
813  /* This checks both copyObject() and the equal() routines... */
814  if (!equal(new_plan, plan))
815  elog(WARNING, "copyObject() failed to produce an equal plan tree");
816  else
817 #endif
818  plan = new_plan;
819  }
820 #endif
821 
822  /*
823  * Print plan if debugging.
824  */
825  if (Debug_print_plan)
826  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
827 
828  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
829 
830  return plan;
831 }
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:71
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2934
void ShowUsage(const char *title)
Definition: postgres.c:4388
#define LOG
Definition: elog.h:26
PlannedStmt * planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:176
void * copyObject(const void *from)
Definition: copyfuncs.c:4605
void ResetUsage(void)
Definition: postgres.c:4381
bool Debug_print_plan
Definition: guc.c:436
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:846
#define WARNING
Definition: elog.h:40
CmdType commandType
Definition: parsenodes.h:103
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
bool Debug_pretty_print
Definition: guc.c:439
#define elog
Definition: elog.h:219
bool log_planner_stats
Definition: guc.c:442
void PostgresMain ( int  argc,
char *  argv[],
const char *  dbname,
const char *  username 
)

Definition at line 3563 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), am_walsender, Assert, BaseInit(), BeginReportingGUCOptions(), BlockSig, buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, CreateDataDirLockFile(), DataDir, debug_query_string, DestDebug, DestNone, DestRemote, die(), disable_all_timeouts(), disable_timeout(), doing_extended_query_message, DoingCommandRead, drop_unnamed_stmt(), DropPreparedStatement(), EmitErrorReport(), enable_timeout_after(), ereport, errcode(), errmsg(), ERROR, error_context_stack, exec_bind_message(), exec_describe_portal_message(), exec_describe_statement_message(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), FATAL, finish_xact_command(), FloatExceptionHandler(), FlushErrorState(), forbidden_in_wal_sender(), GetCurrentTimestamp(), GetPortalByName(), got_SIGHUP, HandleFunctionRequest(), HOLD_INTERRUPTS, i, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IdleInTransactionSessionTimeout, ignore_till_sync, InitializeGUCOptions(), InitializeMaxBackends(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InitStandaloneProcess(), initStringInfo(), InitWalSender(), InvalidateCatalogSnapshotConditionally(), InvalidOid, IsAbortedTransactionBlockState(), IsTransactionOrTransactionBlock(), IsUnderPostmaster, Log_disconnections, log_disconnections(), MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MessageContext, MyCancelKey, MyProcPid, MyReplicationSlot, NormalProcessing, NULL, on_proc_exit(), palloc(), PG_exception_stack, PG_SETMASK, PGC_POSTMASTER, PGC_SIGHUP, PgStartTime, pgstat_report_activity(), pgstat_report_stat(), PortalDrop(), PortalIsValid, PostmasterContext, pq_beginmessage(), pq_comm_reset, pq_endmessage(), pq_flush, pq_getmsgbyte(), pq_getmsgend(), pq_getmsgint(), pq_getmsgstring(), pq_is_reading_msg(), pq_putemptymessage(), pq_sendint(), pqinitmask(), pqsignal(), proc_exit(), process_postgres_switches(), process_session_preload_libraries(), ProcessCompletedNotifies(), ProcessConfigFile(), procsignal_sigusr1_handler(), progname, QueryCancelPending, quickdie(), ReadCommand(), ReadyForQuery(), ReplicationSlotCleanup(), ReplicationSlotRelease(), RESUME_INTERRUPTS, SelectConfigFiles(), set_ps_display(), SetCurrentStatementStartTimestamp(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SigHupHandler(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, start_xact_command(), STATE_FASTPATH, STATE_IDLE, STATE_IDLEINTRANSACTION, STATE_IDLEINTRANSACTION_ABORTED, StatementCancelHandler(), TopMemoryContext, UnBlockSig, userDoption, username, ValidatePgVersion(), WalSndErrorCleanup(), WalSndSignals(), whereToSendOutput, and xact_started.

Referenced by BackendRun(), and main().

3566 {
3567  int firstchar;
3568  StringInfoData input_message;
3569  sigjmp_buf local_sigjmp_buf;
3570  volatile bool send_ready_for_query = true;
3571  bool disable_idle_in_transaction_timeout = false;
3572 
3573  /* Initialize startup process environment if necessary. */
3574  if (!IsUnderPostmaster)
3575  InitStandaloneProcess(argv[0]);
3576 
3578 
3579  /*
3580  * Set default values for command-line options.
3581  */
3582  if (!IsUnderPostmaster)
3584 
3585  /*
3586  * Parse command-line options.
3587  */
3589 
3590  /* Must have gotten a database name, or have a default (the username) */
3591  if (dbname == NULL)
3592  {
3593  dbname = username;
3594  if (dbname == NULL)
3595  ereport(FATAL,
3596  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3597  errmsg("%s: no database nor user name specified",
3598  progname)));
3599  }
3600 
3601  /* Acquire configuration parameters, unless inherited from postmaster */
3602  if (!IsUnderPostmaster)
3603  {
3605  proc_exit(1);
3606  }
3607 
3608  /*
3609  * Set up signal handlers and masks.
3610  *
3611  * Note that postmaster blocked all signals before forking child process,
3612  * so there is no race condition whereby we might receive a signal before
3613  * we have set up the handler.
3614  *
3615  * Also note: it's best not to use any signals that are SIG_IGNored in the
3616  * postmaster. If such a signal arrives before we are able to change the
3617  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3618  * handler in the postmaster to reserve the signal. (Of course, this isn't
3619  * an issue for signals that are locally generated, such as SIGALRM and
3620  * SIGPIPE.)
3621  */
3622  if (am_walsender)
3623  WalSndSignals();
3624  else
3625  {
3626  pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3627  * file */
3628  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3629  pqsignal(SIGTERM, die); /* cancel current query and exit */
3630 
3631  /*
3632  * In a standalone backend, SIGQUIT can be generated from the keyboard
3633  * easily, while SIGTERM cannot, so we make both signals do die()
3634  * rather than quickdie().
3635  */
3636  if (IsUnderPostmaster)
3637  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3638  else
3639  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3640  InitializeTimeouts(); /* establishes SIGALRM handler */
3641 
3642  /*
3643  * Ignore failure to write to frontend. Note: if frontend closes
3644  * connection, we will notice it and exit cleanly when control next
3645  * returns to outer loop. This seems safer than forcing exit in the
3646  * midst of output during who-knows-what operation...
3647  */
3652 
3653  /*
3654  * Reset some signals that are accepted by postmaster but not by
3655  * backend
3656  */
3657  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3658  * platforms */
3659  }
3660 
3661  pqinitmask();
3662 
3663  if (IsUnderPostmaster)
3664  {
3665  /* We allow SIGQUIT (quickdie) at all times */
3666  sigdelset(&BlockSig, SIGQUIT);
3667  }
3668 
3669  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3670 
3671  if (!IsUnderPostmaster)
3672  {
3673  /*
3674  * Validate we have been given a reasonable-looking DataDir (if under
3675  * postmaster, assume postmaster did this already).
3676  */
3677  Assert(DataDir);
3679 
3680  /* Change into DataDir (if under postmaster, was done already) */
3681  ChangeToDataDir();
3682 
3683  /*
3684  * Create lockfile for data directory.
3685  */
3686  CreateDataDirLockFile(false);
3687 
3688  /* Initialize MaxBackends (if under postmaster, was done already) */
3690  }
3691 
3692  /* Early initialization */
3693  BaseInit();
3694 
3695  /*
3696  * Create a per-backend PGPROC struct in shared memory, except in the
3697  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3698  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3699  * had to do some stuff with LWLocks).
3700  */
3701 #ifdef EXEC_BACKEND
3702  if (!IsUnderPostmaster)
3703  InitProcess();
3704 #else
3705  InitProcess();
3706 #endif
3707 
3708  /* We need to allow SIGINT, etc during the initial transaction */
3710 
3711  /*
3712  * General initialization.
3713  *
3714  * NOTE: if you are tempted to add code in this vicinity, consider putting
3715  * it inside InitPostgres() instead. In particular, anything that
3716  * involves database access should be there, not here.
3717  */
3719 
3720  /*
3721  * If the PostmasterContext is still around, recycle the space; we don't
3722  * need it anymore after InitPostgres completes. Note this does not trash
3723  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3724  * ... else we'd need to copy the Port data first. Also, subsidiary data
3725  * such as the username isn't lost either; see ProcessStartupPacket().
3726  */
3727  if (PostmasterContext)
3728  {
3731  }
3732 
3734 
3735  /*
3736  * Now all GUC states are fully set up. Report them to client if
3737  * appropriate.
3738  */
3740 
3741  /*
3742  * Also set up handler to log session end; we have to wait till now to be
3743  * sure Log_disconnections has its final value.
3744  */
3747 
3748  /* Perform initialization specific to a WAL sender process. */
3749  if (am_walsender)
3750  InitWalSender();
3751 
3752  /*
3753  * process any libraries that should be preloaded at backend start (this
3754  * likewise can't be done until GUC settings are complete)
3755  */
3757 
3758  /*
3759  * Send this backend's cancellation info to the frontend.
3760  */
3762  {
3764 
3765  pq_beginmessage(&buf, 'K');
3766  pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3767  pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3768  pq_endmessage(&buf);
3769  /* Need not flush since ReadyForQuery will do it. */
3770  }
3771 
3772  /* Welcome banner for standalone case */
3774  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3775 
3776  /*
3777  * Create the memory context we will use in the main loop.
3778  *
3779  * MessageContext is reset once per iteration of the main loop, ie, upon
3780  * completion of processing of each command message from the client.
3781  */
3783  "MessageContext",
3785 
3786  /*
3787  * Remember stand-alone backend startup time
3788  */
3789  if (!IsUnderPostmaster)
3791 
3792  /*
3793  * POSTGRES main processing loop begins here
3794  *
3795  * If an exception is encountered, processing resumes here so we abort the
3796  * current transaction and start a new one.
3797  *
3798  * You might wonder why this isn't coded as an infinite loop around a
3799  * PG_TRY construct. The reason is that this is the bottom of the
3800  * exception stack, and so with PG_TRY there would be no exception handler
3801  * in force at all during the CATCH part. By leaving the outermost setjmp
3802  * always active, we have at least some chance of recovering from an error
3803  * during error recovery. (If we get into an infinite loop thereby, it
3804  * will soon be stopped by overflow of elog.c's internal state stack.)
3805  *
3806  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3807  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3808  * is essential in case we longjmp'd out of a signal handler on a platform
3809  * where that leaves the signal blocked. It's not redundant with the
3810  * unblock in AbortTransaction() because the latter is only called if we
3811  * were inside a transaction.
3812  */
3813 
3814  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3815  {
3816  /*
3817  * NOTE: if you are tempted to add more code in this if-block,
3818  * consider the high probability that it should be in
3819  * AbortTransaction() instead. The only stuff done directly here
3820  * should be stuff that is guaranteed to apply *only* for outer-level
3821  * error recovery, such as adjusting the FE/BE protocol status.
3822  */
3823 
3824  /* Since not using PG_TRY, must reset error stack by hand */
3826 
3827  /* Prevent interrupts while cleaning up */
3828  HOLD_INTERRUPTS();
3829 
3830  /*
3831  * Forget any pending QueryCancel request, since we're returning to
3832  * the idle loop anyway, and cancel any active timeout requests. (In
3833  * future we might want to allow some timeout requests to survive, but
3834  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3835  * we got here because of a query cancel interrupting the SIGALRM
3836  * interrupt handler.) Note in particular that we must clear the
3837  * statement and lock timeout indicators, to prevent any future plain
3838  * query cancels from being misreported as timeouts in case we're
3839  * forgetting a timeout cancel.
3840  */
3841  disable_all_timeouts(false);
3842  QueryCancelPending = false; /* second to avoid race condition */
3843 
3844  /* Not reading from the client anymore. */
3845  DoingCommandRead = false;
3846 
3847  /* Make sure libpq is in a good state */
3848  pq_comm_reset();
3849 
3850  /* Report the error to the client and/or server log */
3851  EmitErrorReport();
3852 
3853  /*
3854  * Make sure debug_query_string gets reset before we possibly clobber
3855  * the storage it points at.
3856  */
3858 
3859  /*
3860  * Abort the current transaction in order to recover.
3861  */
3863 
3864  if (am_walsender)
3866 
3867  /*
3868  * We can't release replication slots inside AbortTransaction() as we
3869  * need to be able to start and abort transactions while having a slot
3870  * acquired. But we never need to hold them across top level errors,
3871  * so releasing here is fine. There's another cleanup in ProcKill()
3872  * ensuring we'll correctly cleanup on FATAL errors as well.
3873  */
3874  if (MyReplicationSlot != NULL)
3876 
3877  /* We also want to cleanup temporary slots on error. */
3879 
3880  /*
3881  * Now return to normal top-level context and clear ErrorContext for
3882  * next time.
3883  */
3885  FlushErrorState();
3886 
3887  /*
3888  * If we were handling an extended-query-protocol message, initiate
3889  * skip till next Sync. This also causes us not to issue
3890  * ReadyForQuery (until we get Sync).
3891  */
3893  ignore_till_sync = true;
3894 
3895  /* We don't have a transaction command open anymore */
3896  xact_started = false;
3897 
3898  /*
3899  * If an error occurred while we were reading a message from the
3900  * client, we have potentially lost track of where the previous
3901  * message ends and the next one begins. Even though we have
3902  * otherwise recovered from the error, we cannot safely read any more
3903  * messages from the client, so there isn't much we can do with the
3904  * connection anymore.
3905  */
3906  if (pq_is_reading_msg())
3907  ereport(FATAL,
3908  (errcode(ERRCODE_PROTOCOL_VIOLATION),
3909  errmsg("terminating connection because protocol synchronization was lost")));
3910 
3911  /* Now we can allow interrupts again */
3913  }
3914 
3915  /* We can now handle ereport(ERROR) */
3916  PG_exception_stack = &local_sigjmp_buf;
3917 
3918  if (!ignore_till_sync)
3919  send_ready_for_query = true; /* initially, or after error */
3920 
3921  /*
3922  * Non-error queries loop here.
3923  */
3924 
3925  for (;;)
3926  {
3927  /*
3928  * At top of loop, reset extended-query-message flag, so that any
3929  * errors encountered in "idle" state don't provoke skip.
3930  */
3932 
3933  /*
3934  * Release storage left over from prior query cycle, and create a new
3935  * query input buffer in the cleared MessageContext.
3936  */
3939 
3940  initStringInfo(&input_message);
3941 
3942  /*
3943  * Also consider releasing our catalog snapshot if any, so that it's
3944  * not preventing advance of global xmin while we wait for the client.
3945  */
3947 
3948  /*
3949  * (1) If we've reached idle state, tell the frontend we're ready for
3950  * a new query.
3951  *
3952  * Note: this includes fflush()'ing the last of the prior output.
3953  *
3954  * This is also a good time to send collected statistics to the
3955  * collector, and to update the PS stats display. We avoid doing
3956  * those every time through the message loop because it'd slow down
3957  * processing of batched messages, and because we don't want to report
3958  * uncommitted updates (that confuses autovacuum). The notification
3959  * processor wants a call too, if we are not in a transaction block.
3960  */
3961  if (send_ready_for_query)
3962  {
3964  {
3965  set_ps_display("idle in transaction (aborted)", false);
3967 
3968  /* Start the idle-in-transaction timer */
3970  {
3971  disable_idle_in_transaction_timeout = true;
3974  }
3975  }
3977  {
3978  set_ps_display("idle in transaction", false);
3980 
3981  /* Start the idle-in-transaction timer */
3983  {
3984  disable_idle_in_transaction_timeout = true;
3987  }
3988  }
3989  else
3990  {
3992  pgstat_report_stat(false);
3993 
3994  set_ps_display("idle", false);
3996  }
3997 
3999  send_ready_for_query = false;
4000  }
4001 
4002  /*
4003  * (2) Allow asynchronous signals to be executed immediately if they
4004  * come in while we are waiting for client input. (This must be
4005  * conditional since we don't want, say, reads on behalf of COPY FROM
4006  * STDIN doing the same thing.)
4007  */
4008  DoingCommandRead = true;
4009 
4010  /*
4011  * (3) read a command (loop blocks here)
4012  */
4013  firstchar = ReadCommand(&input_message);
4014 
4015  /*
4016  * (4) disable async signal conditions again.
4017  *
4018  * Query cancel is supposed to be a no-op when there is no query in
4019  * progress, so if a query cancel arrived while we were idle, just
4020  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4021  * it's called when DoingCommandRead is set, so check for interrupts
4022  * before resetting DoingCommandRead.
4023  */
4025  DoingCommandRead = false;
4026 
4027  /*
4028  * (5) turn off the idle-in-transaction timeout
4029  */
4030  if (disable_idle_in_transaction_timeout)
4031  {
4033  disable_idle_in_transaction_timeout = false;
4034  }
4035 
4036  /*
4037  * (6) check for any other interesting events that happened while we
4038  * slept.
4039  */
4040  if (got_SIGHUP)
4041  {
4042  got_SIGHUP = false;
4044  }
4045 
4046  /*
4047  * (7) process the command. But ignore it if we're skipping till
4048  * Sync.
4049  */
4050  if (ignore_till_sync && firstchar != EOF)
4051  continue;
4052 
4053  switch (firstchar)
4054  {
4055  case 'Q': /* simple query */
4056  {
4057  const char *query_string;
4058 
4059  /* Set statement_timestamp() */
4061 
4062  query_string = pq_getmsgstring(&input_message);
4063  pq_getmsgend(&input_message);
4064 
4065  if (am_walsender)
4066  {
4067  if (!exec_replication_command(query_string))
4068  exec_simple_query(query_string);
4069  }
4070  else
4071  exec_simple_query(query_string);
4072 
4073  send_ready_for_query = true;
4074  }
4075  break;
4076 
4077  case 'P': /* parse */
4078  {
4079  const char *stmt_name;
4080  const char *query_string;
4081  int numParams;
4082  Oid *paramTypes = NULL;
4083 
4084  forbidden_in_wal_sender(firstchar);
4085 
4086  /* Set statement_timestamp() */
4088 
4089  stmt_name = pq_getmsgstring(&input_message);
4090  query_string = pq_getmsgstring(&input_message);
4091  numParams = pq_getmsgint(&input_message, 2);
4092  if (numParams > 0)
4093  {
4094  int i;
4095 
4096  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4097  for (i = 0; i < numParams; i++)
4098  paramTypes[i] = pq_getmsgint(&input_message, 4);
4099  }
4100  pq_getmsgend(&input_message);
4101 
4102  exec_parse_message(query_string, stmt_name,
4103  paramTypes, numParams);
4104  }
4105  break;
4106 
4107  case 'B': /* bind */
4108  forbidden_in_wal_sender(firstchar);
4109 
4110  /* Set statement_timestamp() */
4112 
4113  /*
4114  * this message is complex enough that it seems best to put
4115  * the field extraction out-of-line
4116  */
4117  exec_bind_message(&input_message);
4118  break;
4119 
4120  case 'E': /* execute */
4121  {
4122  const char *portal_name;
4123  int max_rows;
4124 
4125  forbidden_in_wal_sender(firstchar);
4126 
4127  /* Set statement_timestamp() */
4129 
4130  portal_name = pq_getmsgstring(&input_message);
4131  max_rows = pq_getmsgint(&input_message, 4);
4132  pq_getmsgend(&input_message);
4133 
4134  exec_execute_message(portal_name, max_rows);
4135  }
4136  break;
4137 
4138  case 'F': /* fastpath function call */
4139  forbidden_in_wal_sender(firstchar);
4140 
4141  /* Set statement_timestamp() */
4143 
4144  /* Report query to various monitoring facilities. */
4146  set_ps_display("<FASTPATH>", false);
4147 
4148  /* start an xact for this function invocation */
4150 
4151  /*
4152  * Note: we may at this point be inside an aborted
4153  * transaction. We can't throw error for that until we've
4154  * finished reading the function-call message, so
4155  * HandleFunctionRequest() must check for it after doing so.
4156  * Be careful not to do anything that assumes we're inside a
4157  * valid transaction here.
4158  */
4159 
4160  /* switch back to message context */
4162 
4163  if (HandleFunctionRequest(&input_message) == EOF)
4164  {
4165  /* lost frontend connection during F message input */
4166 
4167  /*
4168  * Reset whereToSendOutput to prevent ereport from
4169  * attempting to send any more messages to client.
4170  */
4173 
4174  proc_exit(0);
4175  }
4176 
4177  /* commit the function-invocation transaction */
4179 
4180  send_ready_for_query = true;
4181  break;
4182 
4183  case 'C': /* close */
4184  {
4185  int close_type;
4186  const char *close_target;
4187 
4188  forbidden_in_wal_sender(firstchar);
4189 
4190  close_type = pq_getmsgbyte(&input_message);
4191  close_target = pq_getmsgstring(&input_message);
4192  pq_getmsgend(&input_message);
4193 
4194  switch (close_type)
4195  {
4196  case 'S':
4197  if (close_target[0] != '\0')
4198  DropPreparedStatement(close_target, false);
4199  else
4200  {
4201  /* special-case the unnamed statement */
4203  }
4204  break;
4205  case 'P':
4206  {
4207  Portal portal;
4208 
4209  portal = GetPortalByName(close_target);
4210  if (PortalIsValid(portal))
4211  PortalDrop(portal, false);
4212  }
4213  break;
4214  default:
4215  ereport(ERROR,
4216  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4217  errmsg("invalid CLOSE message subtype %d",
4218  close_type)));
4219  break;
4220  }
4221 
4223  pq_putemptymessage('3'); /* CloseComplete */
4224  }
4225  break;
4226 
4227  case 'D': /* describe */
4228  {
4229  int describe_type;
4230  const char *describe_target;
4231 
4232  forbidden_in_wal_sender(firstchar);
4233 
4234  /* Set statement_timestamp() (needed for xact) */
4236 
4237  describe_type = pq_getmsgbyte(&input_message);
4238  describe_target = pq_getmsgstring(&input_message);
4239  pq_getmsgend(&input_message);
4240 
4241  switch (describe_type)
4242  {
4243  case 'S':
4244  exec_describe_statement_message(describe_target);
4245  break;
4246  case 'P':
4247  exec_describe_portal_message(describe_target);
4248  break;
4249  default:
4250  ereport(ERROR,
4251  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4252  errmsg("invalid DESCRIBE message subtype %d",
4253  describe_type)));
4254  break;
4255  }
4256  }
4257  break;
4258 
4259  case 'H': /* flush */
4260  pq_getmsgend(&input_message);
4262  pq_flush();
4263  break;
4264 
4265  case 'S': /* sync */
4266  pq_getmsgend(&input_message);
4268  send_ready_for_query = true;
4269  break;
4270 
4271  /*
4272  * 'X' means that the frontend is closing down the socket. EOF
4273  * means unexpected loss of frontend connection. Either way,
4274  * perform normal shutdown.
4275  */
4276  case 'X':
4277  case EOF:
4278 
4279  /*
4280  * Reset whereToSendOutput to prevent ereport from attempting
4281  * to send any more messages to client.
4282  */
4285 
4286  /*
4287  * NOTE: if you are tempted to add more code here, DON'T!
4288  * Whatever you had in mind to do should be set up as an
4289  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4290  * it will fail to be called during other backend-shutdown
4291  * scenarios.
4292  */
4293  proc_exit(0);
4294 
4295  case 'd': /* copy data */
4296  case 'c': /* copy done */
4297  case 'f': /* copy fail */
4298 
4299  /*
4300  * Accept but ignore these messages, per protocol spec; we
4301  * probably got here because a COPY failed, and the frontend
4302  * is still sending data.
4303  */
4304  break;
4305 
4306  default:
4307  ereport(FATAL,
4308  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4309  errmsg("invalid frontend message type %d",
4310  firstchar)));
4311  }
4312  } /* end of input-reading loop */
4313 }
void InitializeTimeouts(void)
Definition: timeout.c:340
void AbortCurrentTransaction(void)
Definition: xact.c:2986
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2385
#define SIGUSR1
Definition: win32.h:211
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
void BeginReportingGUCOptions(void)
Definition: guc.c:5339
int MyProcPid
Definition: globals.c:38
#define pq_flush()
Definition: libpq.h:39
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:502
static void finish_xact_command(void)
Definition: postgres.c:2454
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1363
static volatile sig_atomic_t got_SIGHUP
Definition: postgres.c:129
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:292
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2806
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:621
Portal GetPortalByName(const char *name)
Definition: portalmem.c:129
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:219
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1349
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:370
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4323
void proc_exit(int code)
Definition: ipc.c:99
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4322
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:421
#define SetProcessingMode(mode)
Definition: miscadmin.h:371
void ReplicationSlotCleanup()
Definition: slot.c:413
void BaseInit(void)
Definition: postinit.c:517
unsigned int Oid
Definition: postgres_ext.h:31
volatile bool QueryCancelPending
Definition: globals.c:30
const char * progname
Definition: pg_standby.c:37
#define SIGQUIT
Definition: win32.h:197
void FlushErrorState(void)
Definition: elog.c:1587
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2650
signed int int32
Definition: c.h:256
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1842
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4483
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:116
ErrorContextCallback * error_context_stack
Definition: elog.c:88
void pqinitmask(void)
Definition: pqsignal.c:41
bool am_walsender
Definition: walsender.c:108
#define SIG_IGN
Definition: win32.h:193
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:596
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1080
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1231
int IdleInTransactionSessionTimeout
Definition: proc.c:63
int32 MyCancelKey
Definition: globals.c:41
void WalSndSignals(void)
Definition: walsender.c:2810
#define FATAL
Definition: elog.h:52
static void SigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2684
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
void InitProcess(void)
Definition: proc.c:287
Definition: dest.h:88
static char * buf
Definition: pg_test_fsync.c:65
bool IsUnderPostmaster
Definition: globals.c:100
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1459
Definition: dest.h:89
void ChangeToDataDir(void)
Definition: miscinit.c:115
void ReplicationSlotRelease(void)
Definition: slot.c:375
sigset_t UnBlockSig
Definition: pqsignal.c:22
static bool xact_started
Definition: postgres.c:135
void InitWalSender(void)
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
const char * debug_query_string
Definition: postgres.c:83
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1197
#define PortalIsValid(p)
Definition: portal.h:198
static void start_xact_command(void)
Definition: postgres.c:2436
static bool doing_extended_query_message
Definition: postgres.c:148
sigset_t BlockSig
Definition: pqsignal.c:22
void process_session_preload_libraries(void)
Definition: miscinit.c:1494
void WalSndErrorCleanup(void)
Definition: walsender.c:283
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:4668
void EmitErrorReport(void)
Definition: elog.c:1446
TimestampTz PgStartTime
Definition: timestamp.c:48
#define SIGPIPE
Definition: win32.h:201
#define SIGHUP
Definition: win32.h:196
static char * username
Definition: initdb.c:131
#define InvalidOid
Definition: postgres_ext.h:36
#define SIG_DFL
Definition: win32.h:191
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:432
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define pq_comm_reset()
Definition: libpq.h:38
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void ProcessCompletedNotifies(void)
Definition: async.c:1096
void InvalidateCatalogSnapshotConditionally(void)
Definition: snapmgr.c:527
static bool DoingCommandRead
Definition: postgres.c:142
void InitializeMaxBackends(void)
Definition: postinit.c:495
char * dbname
Definition: streamutil.c:38
MemoryContext MessageContext
Definition: mcxt.c:47
sigjmp_buf * PG_exception_stack
Definition: elog.c:90
static const char * userDoption
Definition: postgres.c:159
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:740
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:558
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:461
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:236
void ReadyForQuery(CommandDest dest)
Definition: dest.c:241
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:344
void die(SIGNAL_ARGS)
Definition: postgres.c:2619
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2671
static void drop_unnamed_stmt(void)
Definition: postgres.c:2533
char * DataDir
Definition: globals.c:59
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:448
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
bool Log_disconnections
Definition: postgres.c:89
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3304
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:677
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:260
CommandDest whereToSendOutput
Definition: postgres.c:86
#define SIGCHLD
Definition: win32.h:206
static bool ignore_till_sync
Definition: postgres.c:149
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2558
MemoryContext PostmasterContext
Definition: mcxt.c:45
#define SIGUSR2
Definition: win32.h:212
static void exec_simple_query(const char *query_string)
Definition: postgres.c:880
int HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:270
void InitializeGUCOptions(void)
Definition: guc.c:4446
void pgstat_report_stat(bool force)
Definition: pgstat.c:748
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:579
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2292
void process_postgres_switches ( int  argc,
char *  argv[],
GucContext  ctx,
const char **  dbname 
)

Definition at line 3304 of file postgres.c.

References EchoQuery, ereport, errcode(), errhint(), errmsg(), ERROR, FATAL, flag(), free, FrontendProtocol, get_stats_option_name(), getopt(), IsBinaryUpgrade, IsUnderPostmaster, MAXPGPATH, name, NULL, optarg, opterr, optind, OutputFileName, ParseLongOption(), PGC_POSTMASTER, PGC_S_ARGV, PGC_S_CLIENT, progname, set_debug_options(), set_plan_disabling_options(), SetConfigOption(), strlcpy(), userDoption, UseSemiNewlineNewline, and value.

Referenced by PostgresMain(), and process_startup_options().

3306 {
3307  bool secure = (ctx == PGC_POSTMASTER);
3308  int errs = 0;
3309  GucSource gucsource;
3310  int flag;
3311 
3312  if (secure)
3313  {
3314  gucsource = PGC_S_ARGV; /* switches came from command line */
3315 
3316  /* Ignore the initial --single argument, if present */
3317  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3318  {
3319  argv++;
3320  argc--;
3321  }
3322  }
3323  else
3324  {
3325  gucsource = PGC_S_CLIENT; /* switches came from client */
3326  }
3327 
3328 #ifdef HAVE_INT_OPTERR
3329 
3330  /*
3331  * Turn this off because it's either printed to stderr and not the log
3332  * where we'd want it, or argv[0] is now "--single", which would make for
3333  * a weird error message. We print our own error message below.
3334  */
3335  opterr = 0;
3336 #endif
3337 
3338  /*
3339  * Parse command-line options. CAUTION: keep this in sync with
3340  * postmaster/postmaster.c (the option sets should not conflict) and with
3341  * the common help() function in main/main.c.
3342  */
3343  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3344  {
3345  switch (flag)
3346  {
3347  case 'B':
3348  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3349  break;
3350 
3351  case 'b':
3352  /* Undocumented flag used for binary upgrades */
3353  if (secure)
3354  IsBinaryUpgrade = true;
3355  break;
3356 
3357  case 'C':
3358  /* ignored for consistency with the postmaster */
3359  break;
3360 
3361  case 'D':
3362  if (secure)
3363  userDoption = strdup(optarg);
3364  break;
3365 
3366  case 'd':
3367  set_debug_options(atoi(optarg), ctx, gucsource);
3368  break;
3369 
3370  case 'E':
3371  if (secure)
3372  EchoQuery = true;
3373  break;
3374 
3375  case 'e':
3376  SetConfigOption("datestyle", "euro", ctx, gucsource);
3377  break;
3378 
3379  case 'F':
3380  SetConfigOption("fsync", "false", ctx, gucsource);
3381  break;
3382 
3383  case 'f':
3384  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3385  errs++;
3386  break;
3387 
3388  case 'h':
3389  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3390  break;
3391 
3392  case 'i':
3393  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3394  break;
3395 
3396  case 'j':
3397  if (secure)
3398  UseSemiNewlineNewline = true;
3399  break;
3400 
3401  case 'k':
3402  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3403  break;
3404 
3405  case 'l':
3406  SetConfigOption("ssl", "true", ctx, gucsource);
3407  break;
3408 
3409  case 'N':
3410  SetConfigOption("max_connections", optarg, ctx, gucsource);
3411  break;
3412 
3413  case 'n':
3414  /* ignored for consistency with postmaster */
3415  break;
3416 
3417  case 'O':
3418  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3419  break;
3420 
3421  case 'o':
3422  errs++;
3423  break;
3424 
3425  case 'P':
3426  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3427  break;
3428 
3429  case 'p':
3430  SetConfigOption("port", optarg, ctx, gucsource);
3431  break;
3432 
3433  case 'r':
3434  /* send output (stdout and stderr) to the given file */
3435  if (secure)
3437  break;
3438 
3439  case 'S':
3440  SetConfigOption("work_mem", optarg, ctx, gucsource);
3441  break;
3442 
3443  case 's':
3444  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3445  break;
3446 
3447  case 'T':
3448  /* ignored for consistency with the postmaster */
3449  break;
3450 
3451  case 't':
3452  {
3453  const char *tmp = get_stats_option_name(optarg);
3454 
3455  if (tmp)
3456  SetConfigOption(tmp, "true", ctx, gucsource);
3457  else
3458  errs++;
3459  break;
3460  }
3461 
3462  case 'v':
3463 
3464  /*
3465  * -v is no longer used in normal operation, since
3466  * FrontendProtocol is already set before we get here. We keep
3467  * the switch only for possible use in standalone operation,
3468  * in case we ever support using normal FE/BE protocol with a
3469  * standalone backend.
3470  */
3471  if (secure)
3473  break;
3474 
3475  case 'W':
3476  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3477  break;
3478 
3479  case 'c':
3480  case '-':
3481  {
3482  char *name,
3483  *value;
3484 
3485  ParseLongOption(optarg, &name, &value);
3486  if (!value)
3487  {
3488  if (flag == '-')
3489  ereport(ERROR,
3490  (errcode(ERRCODE_SYNTAX_ERROR),
3491  errmsg("--%s requires a value",
3492  optarg)));
3493  else
3494  ereport(ERROR,
3495  (errcode(ERRCODE_SYNTAX_ERROR),
3496  errmsg("-c %s requires a value",
3497  optarg)));
3498  }
3499  SetConfigOption(name, value, ctx, gucsource);
3500  free(name);
3501  if (value)
3502  free(value);
3503  break;
3504  }
3505 
3506  default:
3507  errs++;
3508  break;
3509  }
3510 
3511  if (errs)
3512  break;
3513  }
3514 
3515  /*
3516  * Optional database name should be there only if *dbname is NULL.
3517  */
3518  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3519  *dbname = strdup(argv[optind++]);
3520 
3521  if (errs || argc != optind)
3522  {
3523  if (errs)
3524  optind--; /* complain about the previous argument */
3525 
3526  /* spell the error message a bit differently depending on context */
3527  if (IsUnderPostmaster)
3528  ereport(FATAL,
3529  (errcode(ERRCODE_SYNTAX_ERROR),
3530  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3531  errhint("Try \"%s --help\" for more information.", progname)));
3532  else
3533  ereport(FATAL,
3534  (errcode(ERRCODE_SYNTAX_ERROR),
3535  errmsg("%s: invalid command-line argument: %s",
3536  progname, argv[optind]),
3537  errhint("Try \"%s --help\" for more information.", progname)));
3538  }
3539 
3540  /*
3541  * Reset getopt(3) library so that it will work correctly in subprocesses
3542  * or when this function is called a second time with another array.
3543  */
3544  optind = 1;
3545 #ifdef HAVE_INT_OPTRESET
3546  optreset = 1; /* some systems need this too */
3547 #endif
3548 }
int errhint(const char *fmt,...)
Definition: elog.c:987
static struct @78 value
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:9349
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3222
int errcode(int sqlerrcode)
Definition: elog.c:575
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3264
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3193
const char * progname
Definition: pg_standby.c:37
bool IsBinaryUpgrade
Definition: globals.c:101
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
GucSource
Definition: guc.h:105
int optind
Definition: getopt.c:51
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
char OutputFileName[MAXPGPATH]
Definition: globals.c:61
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6651
bool IsUnderPostmaster
Definition: globals.c:100
char * flag(int b)
Definition: test-ctype.c:33
int opterr
Definition: getopt.c:50
#define ereport(elevel, rest)
Definition: elog.h:122
uint32 ProtocolVersion
Definition: pqcomm.h:113
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define NULL
Definition: c.h:229
char * dbname
Definition: streamutil.c:38
const char * name
Definition: encode.c:521
static bool EchoQuery
Definition: postgres.c:160
static const char * userDoption
Definition: postgres.c:159
static bool UseSemiNewlineNewline
Definition: postgres.c:161
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * optarg
Definition: getopt.c:53
ProtocolVersion FrontendProtocol
Definition: globals.c:27
void ProcessClientReadInterrupt ( bool  blocked)

Definition at line 522 of file postgres.c.

References catchupInterruptPending, CHECK_FOR_INTERRUPTS, DoingCommandRead, notifyInterruptPending, ProcDiePending, ProcessCatchupInterrupt(), and ProcessNotifyInterrupt().

Referenced by interactive_getc(), and secure_read().

523 {
524  int save_errno = errno;
525 
526  if (DoingCommandRead)
527  {
528  /* Check for general interrupts that arrived while reading */
530 
531  /* Process sinval catchup interrupts that happened while reading */
534 
535  /* Process sinval catchup interrupts that happened while reading */
538  }
539  else if (ProcDiePending && blocked)
540  {
541  /*
542  * We're dying. It's safe (and sane) to handle that now.
543  */
545  }
546 
547  errno = save_errno;
548 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void ProcessNotifyInterrupt(void)
Definition: async.c:1726
static bool DoingCommandRead
Definition: postgres.c:142
volatile bool ProcDiePending
Definition: globals.c:31
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:356
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 560 of file postgres.c.

References CHECK_FOR_INTERRUPTS, DestNone, DestRemote, ProcDiePending, and whereToSendOutput.

Referenced by secure_write().

561 {
562  int save_errno = errno;
563 
564  /*
565  * We only want to process the interrupt here if socket writes are
566  * blocking to increase the chance to get an error message to the client.
567  * If we're not blocked there'll soon be a CHECK_FOR_INTERRUPTS(). But if
568  * we're blocked we'll never get out of that situation if the client has
569  * died.
570  */
571  if (ProcDiePending && blocked)
572  {
573  /*
574  * We're dying. It's safe (and sane) to handle that now. But we don't
575  * want to send the client the error message as that a) would possibly
576  * block again b) would possibly lead to sending an error message to
577  * the client, while we already started to send something else.
578  */
581 
583  }
584 
585  errno = save_errno;
586 }
Definition: dest.h:88
volatile bool ProcDiePending
Definition: globals.c:31
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
CommandDest whereToSendOutput
Definition: postgres.c:86
void quickdie ( SIGNAL_ARGS  )

Definition at line 2558 of file postgres.c.

References BlockSig, ClientAuthInProgress, DestNone, DestRemote, ereport, errcode(), errdetail(), errhint(), errmsg(), HOLD_INTERRUPTS, on_exit_reset(), PG_SETMASK, SIGQUIT, WARNING, and whereToSendOutput.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), PostgresMain(), and WalSndSignals().

2559 {
2560  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2561  PG_SETMASK(&BlockSig);
2562 
2563  /*
2564  * Prevent interrupts while exiting; though we just blocked signals that
2565  * would queue new interrupts, one may have been pending. We don't want a
2566  * quickdie() downgraded to a mere query cancel.
2567  */
2568  HOLD_INTERRUPTS();
2569 
2570  /*
2571  * If we're aborting out of client auth, don't risk trying to send
2572  * anything to the client; we will likely violate the protocol, not to
2573  * mention that we may have interrupted the guts of OpenSSL or some
2574  * authentication library.
2575  */
2578 
2579  /*
2580  * Ideally this should be ereport(FATAL), but then we'd not get control
2581  * back...
2582  */
2583  ereport(WARNING,
2584  (errcode(ERRCODE_CRASH_SHUTDOWN),
2585  errmsg("terminating connection because of crash of another server process"),
2586  errdetail("The postmaster has commanded this server process to roll back"
2587  " the current transaction and exit, because another"
2588  " server process exited abnormally and possibly corrupted"
2589  " shared memory."),
2590  errhint("In a moment you should be able to reconnect to the"
2591  " database and repeat your command.")));
2592 
2593  /*
2594  * We DO NOT want to run proc_exit() callbacks -- we're here because
2595  * shared memory may be corrupted, so we don't want to try to clean up our
2596  * transaction. Just nail the windows shut and get out of town. Now that
2597  * there's an atexit callback to prevent third-party code from breaking
2598  * things by calling exit() directly, we have to reset the callbacks
2599  * explicitly to make this work as intended.
2600  */
2601  on_exit_reset();
2602 
2603  /*
2604  * Note we do exit(2) not exit(0). This is to force the postmaster into a
2605  * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2606  * backend. This is necessary precisely because we don't clean up our
2607  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2608  * should ensure the postmaster sees this as a crash, too, but no harm in
2609  * being doubly sure.)
2610  */
2611  exit(2);
2612 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SIGQUIT
Definition: win32.h:197
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool ClientAuthInProgress
Definition: postmaster.c:348
void on_exit_reset(void)
Definition: ipc.c:396
Definition: dest.h:88
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
sigset_t BlockSig
Definition: pqsignal.c:22
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
CommandDest whereToSendOutput
Definition: postgres.c:86
void RecoveryConflictInterrupt ( ProcSignalReason  reason)

Definition at line 2701 of file postgres.c.

References Assert, elog, FATAL, HoldingBufferPinThatDelaysRecovery(), InterruptPending, IsAbortedTransactionBlockState(), IsSubTransaction(), IsTransactionOrTransactionBlock(), IsWaitingForLock(), MyLatch, MyProc, proc_exit_inprogress, ProcDiePending, PROCSIG_RECOVERY_CONFLICT_BUFFERPIN, PROCSIG_RECOVERY_CONFLICT_DATABASE, PROCSIG_RECOVERY_CONFLICT_LOCK, PROCSIG_RECOVERY_CONFLICT_SNAPSHOT, PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK, PROCSIG_RECOVERY_CONFLICT_TABLESPACE, QueryCancelPending, PGPROC::recoveryConflictPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, and SetLatch().

Referenced by procsignal_sigusr1_handler().

2702 {
2703  int save_errno = errno;
2704 
2705  /*
2706  * Don't joggle the elbow of proc_exit
2707  */
2708  if (!proc_exit_inprogress)
2709  {
2710  RecoveryConflictReason = reason;
2711  switch (reason)
2712  {
2714 
2715  /*
2716  * If we aren't waiting for a lock we can never deadlock.
2717  */
2718  if (!IsWaitingForLock())
2719  return;
2720 
2721  /* Intentional drop through to check wait for pin */
2722 
2724 
2725  /*
2726  * If we aren't blocking the Startup process there is nothing
2727  * more to do.
2728  */
2730  return;
2731 
2733 
2734  /* Intentional drop through to error handling */
2735 
2739 
2740  /*
2741  * If we aren't in a transaction any longer then ignore.
2742  */
2744  return;
2745 
2746  /*
2747  * If we can abort just the current subtransaction then we are
2748  * OK to throw an ERROR to resolve the conflict. Otherwise
2749  * drop through to the FATAL case.
2750  *
2751  * XXX other times that we can throw just an ERROR *may* be
2752  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2753  * parent transactions
2754  *
2755  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2756  * by parent transactions and the transaction is not
2757  * transaction-snapshot mode
2758  *
2759  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2760  * cursors open in parent transactions
2761  */
2762  if (!IsSubTransaction())
2763  {
2764  /*
2765  * If we already aborted then we no longer need to cancel.
2766  * We do this here since we do not wish to ignore aborted
2767  * subtransactions, which must cause FATAL, currently.
2768  */
2770  return;
2771 
2772  RecoveryConflictPending = true;
2773  QueryCancelPending = true;
2774  InterruptPending = true;
2775  break;
2776  }
2777 
2778  /* Intentional drop through to session cancel */
2779 
2781  RecoveryConflictPending = true;
2782  ProcDiePending = true;
2783  InterruptPending = true;
2784  break;
2785 
2786  default:
2787  elog(FATAL, "unrecognized conflict mode: %d",
2788  (int) reason);
2789  }
2790 
2792 
2793  /*
2794  * All conflicts apart from database cause dynamic errors where the
2795  * command or transaction can be retried at a later point with some
2796  * potential for success. No need to reset this, since non-retryable
2797  * conflict errors are currently FATAL.
2798  */
2799  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2800  RecoveryConflictRetryable = false;
2801  }
2802 
2803  /*
2804  * Set the process latch. This function essentially emulates signal
2805  * handlers like die() and StatementCancelHandler() and it seems prudent
2806  * to behave similarly as they do.
2807  */
2808  SetLatch(MyLatch);
2809 
2810  errno = save_errno;
2811 }
bool IsWaitingForLock(void)
Definition: proc.c:660
PGPROC * MyProc
Definition: proc.c:67
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:370
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4322
volatile bool QueryCancelPending
Definition: globals.c:30
#define FATAL
Definition: elog.h:52
bool recoveryConflictPending
Definition: proc.h:118
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:166
static bool RecoveryConflictPending
Definition: postgres.c:164
static bool RecoveryConflictRetryable
Definition: postgres.c:165
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:379
#define Assert(condition)
Definition: c.h:675
bool proc_exit_inprogress
Definition: ipc.c:40
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:3692
bool IsSubTransaction(void)
Definition: xact.c:4376
volatile bool ProcDiePending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:51
#define elog
Definition: elog.h:219
void ResetUsage ( void  )

Definition at line 4381 of file postgres.c.

References getrusage(), gettimeofday(), NULL, RUSAGE_SELF, Save_r, and Save_t.

Referenced by _bt_leafbuild(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

4382 {
4385 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4377
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4378
#define RUSAGE_SELF
Definition: rusagestub.h:23
#define NULL
Definition: c.h:229
void set_debug_options ( int  debug_flag,
GucContext  context,
GucSource  source 
)

Definition at line 3193 of file postgres.c.

References PGC_POSTMASTER, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3194 {
3195  if (debug_flag > 0)
3196  {
3197  char debugstr[64];
3198 
3199  sprintf(debugstr, "debug%d", debug_flag);
3200  SetConfigOption("log_min_messages", debugstr, context, source);
3201  }
3202  else
3203  SetConfigOption("log_min_messages", "notice", context, source);
3204 
3205  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3206  {
3207  SetConfigOption("log_connections", "true", context, source);
3208  SetConfigOption("log_disconnections", "true", context, source);
3209  }
3210  if (debug_flag >= 2)
3211  SetConfigOption("log_statement", "all", context, source);
3212  if (debug_flag >= 3)
3213  SetConfigOption("debug_print_parse", "true", context, source);
3214  if (debug_flag >= 4)
3215  SetConfigOption("debug_print_plan", "true", context, source);
3216  if (debug_flag >= 5)
3217  SetConfigOption("debug_print_rewritten", "true", context, source);
3218 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6651
bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3222 of file postgres.c.

References NULL, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3223 {
3224  const char *tmp = NULL;
3225 
3226  switch (arg[0])
3227  {
3228  case 's': /* seqscan */
3229  tmp = "enable_seqscan";
3230  break;
3231  case 'i': /* indexscan */
3232  tmp = "enable_indexscan";
3233  break;
3234  case 'o': /* indexonlyscan */
3235  tmp = "enable_indexonlyscan";
3236  break;
3237  case 'b': /* bitmapscan */
3238  tmp = "enable_bitmapscan";
3239  break;
3240  case 't': /* tidscan */
3241  tmp = "enable_tidscan";
3242  break;
3243  case 'n': /* nestloop */
3244  tmp = "enable_nestloop";
3245  break;
3246  case 'm': /* mergejoin */
3247  tmp = "enable_mergejoin";
3248  break;
3249  case 'h': /* hashjoin */
3250  tmp = "enable_hashjoin";
3251  break;
3252  }
3253  if (tmp)
3254  {
3255  SetConfigOption(tmp, "false", context, source);
3256  return true;
3257  }
3258  else
3259  return false;
3260 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6651
#define NULL
Definition: c.h:229
void * arg
void ShowUsage ( const char *  title)

Definition at line 4388 of file postgres.c.

References appendStringInfo(), appendStringInfoString(), StringInfoData::data, ereport, errdetail_internal(), errmsg_internal(), getrusage(), gettimeofday(), initStringInfo(), StringInfoData::len, LOG, NULL, pfree(), rusage::ru_stime, rusage::ru_utime, RUSAGE_SELF, Save_r, and Save_t.

Referenced by _bt_leafbuild(), _SPI_pquery(), btbuild(), exec_bind_message(), exec_execute_message(), exec_parse_message(), exec_simple_query(), pg_analyze_and_rewrite(), pg_analyze_and_rewrite_params(), pg_parse_query(), pg_plan_query(), pg_rewrite_query(), PortalRun(), and PortalRunMulti().

4389 {
4390  StringInfoData str;
4391  struct timeval user,
4392  sys;
4393  struct timeval elapse_t;
4394  struct rusage r;
4395 
4396  getrusage(RUSAGE_SELF, &r);
4397  gettimeofday(&elapse_t, NULL);
4398  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4399  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4400  if (elapse_t.tv_usec < Save_t.tv_usec)
4401  {
4402  elapse_t.tv_sec--;
4403  elapse_t.tv_usec += 1000000;
4404  }
4405  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4406  {
4407  r.ru_utime.tv_sec--;
4408  r.ru_utime.tv_usec += 1000000;
4409  }
4410  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4411  {
4412  r.ru_stime.tv_sec--;
4413  r.ru_stime.tv_usec += 1000000;
4414  }
4415 
4416  /*
4417  * the only stats we don't show here are for memory usage -- i can't
4418  * figure out how to interpret the relevant fields in the rusage struct,
4419  * and they change names across o/s platforms, anyway. if you can figure
4420  * out what the entries mean, you can somehow extract resident set size,
4421  * shared text size, and unshared data and stack sizes.
4422  */
4423  initStringInfo(&str);
4424 
4425  appendStringInfoString(&str, "! system usage stats:\n");
4426  appendStringInfo(&str,
4427  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4428  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4429  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4430  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4431  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4432  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4433  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4434  appendStringInfo(&str,
4435  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4436  (long) user.tv_sec,
4437  (long) user.tv_usec,
4438  (long) sys.tv_sec,
4439  (long) sys.tv_usec);
4440 #if defined(HAVE_GETRUSAGE)
4441  appendStringInfo(&str,
4442  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4443  r.ru_inblock - Save_r.ru_inblock,
4444  /* they only drink coffee at dec */
4445  r.ru_oublock - Save_r.ru_oublock,
4446  r.ru_inblock, r.ru_oublock);
4447  appendStringInfo(&str,
4448  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4449  r.ru_majflt - Save_r.ru_majflt,
4450  r.ru_minflt - Save_r.ru_minflt,
4451  r.ru_majflt, r.ru_minflt,
4452  r.ru_nswap - Save_r.ru_nswap,
4453  r.ru_nswap);
4454  appendStringInfo(&str,
4455  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4456  r.ru_nsignals - Save_r.ru_nsignals,
4457  r.ru_nsignals,
4458  r.ru_msgrcv - Save_r.ru_msgrcv,
4459  r.ru_msgsnd - Save_r.ru_msgsnd,
4460  r.ru_msgrcv, r.ru_msgsnd);
4461  appendStringInfo(&str,
4462  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4463  r.ru_nvcsw - Save_r.ru_nvcsw,
4464  r.ru_nivcsw - Save_r.ru_nivcsw,
4465  r.ru_nvcsw, r.ru_nivcsw);
4466 #endif /* HAVE_GETRUSAGE */
4467 
4468  /* remove trailing newline */
4469  if (str.data[str.len - 1] == '\n')
4470  str.data[--str.len] = '\0';
4471 
4472  ereport(LOG,
4473  (errmsg_internal("%s", title),
4474  errdetail_internal("%s", str.data)));
4475 
4476  pfree(str.data);
4477 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4377
struct timeval ru_stime
Definition: rusagestub.h:29
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
#define LOG
Definition: elog.h:26
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
void pfree(void *pointer)
Definition: mcxt.c:950
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:189
static struct timeval Save_t
Definition: postgres.c:4378
#define ereport(elevel, rest)
Definition: elog.h:122
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
struct timeval ru_utime
Definition: rusagestub.h:28
#define RUSAGE_SELF
Definition: rusagestub.h:23
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define NULL
Definition: c.h:229
static char * user
Definition: pg_regress.c:92
void StatementCancelHandler ( SIGNAL_ARGS  )

Definition at line 2650 of file postgres.c.

References InterruptPending, MyLatch, proc_exit_inprogress, QueryCancelPending, and SetLatch().

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), PostgresMain(), and StartBackgroundWorker().

2651 {
2652  int save_errno = errno;
2653 
2654  /*
2655  * Don't joggle the elbow of proc_exit
2656  */
2657  if (!proc_exit_inprogress)
2658  {
2659  InterruptPending = true;
2660  QueryCancelPending = true;
2661  }
2662 
2663  /* If we're still here, waken anything waiting on the process latch */
2664  SetLatch(MyLatch);
2665 
2666  errno = save_errno;
2667 }
volatile bool QueryCancelPending
Definition: globals.c:30
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:379
bool proc_exit_inprogress
Definition: ipc.c:40
struct Latch * MyLatch
Definition: globals.c:51

Variable Documentation

int log_statement

Definition at line 91 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

int max_stack_depth

Definition at line 94 of file postgres.c.

Referenced by check_stack_depth().

int PostAuthDelay