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 "utils/queryenvironment.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, QueryEnvironment *queryEnv)
 
Listpg_analyze_and_rewrite_params (RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
 
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 31 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 40 of file tcopprot.h.

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

Function Documentation

void assign_max_stack_depth ( int  newval,
void *  extra 
)

Definition at line 3182 of file postgres.c.

References max_stack_depth_bytes.

3183 {
3184  long newval_bytes = newval * 1024L;
3185 
3186  max_stack_depth_bytes = newval_bytes;
3187 }
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 2106 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().

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

Definition at line 3165 of file postgres.c.

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

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

Definition at line 2623 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().

2624 {
2625  int save_errno = errno;
2626 
2627  /* Don't joggle the elbow of proc_exit */
2628  if (!proc_exit_inprogress)
2629  {
2630  InterruptPending = true;
2631  ProcDiePending = true;
2632  }
2633 
2634  /* If we're still here, waken anything waiting on the process latch */
2635  SetLatch(MyLatch);
2636 
2637  /*
2638  * If we're in single user mode, we want to quit immediately - we can't
2639  * rely on latches as they wouldn't work when stdin/stdout is a file.
2640  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2641  * effort just for the benefit of single user mode.
2642  */
2645 
2646  errno = save_errno;
2647 }
void ProcessInterrupts(void)
Definition: postgres.c:2825
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:367
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 2675 of file postgres.c.

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

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

2676 {
2677  /* We're not returning, so no need to save errno */
2678  ereport(ERROR,
2679  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2680  errmsg("floating-point exception"),
2681  errdetail("An invalid floating-point operation was signaled. "
2682  "This probably means an out-of-range result or an "
2683  "invalid operation, such as division by zero.")));
2684 }
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 4337 of file postgres.c.

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

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

Definition at line 3268 of file postgres.c.

References NULL, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3269 {
3270  switch (arg[0])
3271  {
3272  case 'p':
3273  if (optarg[1] == 'a') /* "parser" */
3274  return "log_parser_stats";
3275  else if (optarg[1] == 'l') /* "planner" */
3276  return "log_planner_stats";
3277  break;
3278 
3279  case 'e': /* "executor" */
3280  return "log_executor_stats";
3281  break;
3282  }
3283 
3284  return NULL;
3285 }
#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,
QueryEnvironment queryEnv 
)

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().

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

Definition at line 681 of file postgres.c.

References Assert, free_parsestate(), log_parser_stats, make_parsestate(), NULL, ParseState::p_queryEnv, 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().

686 {
687  ParseState *pstate;
688  Query *query;
689  List *querytree_list;
690 
691  Assert(query_string != NULL); /* required as of 8.4 */
692 
693  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
694 
695  /*
696  * (1) Perform parse analysis.
697  */
698  if (log_parser_stats)
699  ResetUsage();
700 
701  pstate = make_parsestate(NULL);
702  pstate->p_sourcetext = query_string;
703  pstate->p_queryEnv = queryEnv;
704  (*parserSetup) (pstate, parserSetupArg);
705 
706  query = transformTopLevelStmt(pstate, parsetree);
707 
709  (*post_parse_analyze_hook) (pstate, query);
710 
711  free_parsestate(pstate);
712 
713  if (log_parser_stats)
714  ShowUsage("PARSE ANALYSIS STATISTICS");
715 
716  /*
717  * (2) Rewrite the queries, as necessary
718  */
719  querytree_list = pg_rewrite_query(query);
720 
721  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
722 
723  return querytree_list;
724 }
bool log_parser_stats
Definition: guc.c:442
QueryEnvironment * p_queryEnv
Definition: parse_node.h:192
void ShowUsage(const char *title)
Definition: postgres.c:4380
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4373
const char * p_sourcetext
Definition: parse_node.h:168
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:733
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:187
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
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 = 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:442
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2961
void ShowUsage(const char *title)
Definition: postgres.c:4380
static List * new_list(NodeTag type)
Definition: list.c:63
void ResetUsage(void)
Definition: postgres.c:4373
#define WARNING
Definition: elog.h:40
#define elog
Definition: elog.h:219
#define copyObject(obj)
Definition: nodes.h:621
Definition: pg_list.h:45
List* pg_plan_queries ( List querytrees,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 846 of file postgres.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, lappend(), lfirst_node, 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().

847 {
848  List *stmt_list = NIL;
849  ListCell *query_list;
850 
851  foreach(query_list, querytrees)
852  {
853  Query *query = lfirst_node(Query, query_list);
854  PlannedStmt *stmt;
855 
856  if (query->commandType == CMD_UTILITY)
857  {
858  /* Utility commands require no planning. */
859  stmt = makeNode(PlannedStmt);
860  stmt->commandType = CMD_UTILITY;
861  stmt->canSetTag = query->canSetTag;
862  stmt->utilityStmt = query->utilityStmt;
863  stmt->stmt_location = query->stmt_location;
864  stmt->stmt_len = query->stmt_len;
865  }
866  else
867  {
868  stmt = pg_plan_query(query, cursorOptions, boundParams);
869  }
870 
871  stmt_list = lappend(stmt_list, stmt);
872  }
873 
874  return stmt_list;
875 }
#define NIL
Definition: pg_list.h:69
int stmt_location
Definition: parsenodes.h:180
Node * utilityStmt
Definition: parsenodes.h:118
int stmt_len
Definition: plannodes.h:88
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int stmt_location
Definition: plannodes.h:87
Node * utilityStmt
Definition: plannodes.h:84
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:110
#define makeNode(_type_)
Definition: nodes.h:557
bool canSetTag
Definition: parsenodes.h:116
Definition: pg_list.h:45
int stmt_len
Definition: parsenodes.h:181
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:785
PlannedStmt* pg_plan_query ( Query querytree,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 785 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().

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

Definition at line 3567 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().

3570 {
3571  int firstchar;
3572  StringInfoData input_message;
3573  sigjmp_buf local_sigjmp_buf;
3574  volatile bool send_ready_for_query = true;
3575  bool disable_idle_in_transaction_timeout = false;
3576 
3577  /* Initialize startup process environment if necessary. */
3578  if (!IsUnderPostmaster)
3579  InitStandaloneProcess(argv[0]);
3580 
3582 
3583  /*
3584  * Set default values for command-line options.
3585  */
3586  if (!IsUnderPostmaster)
3588 
3589  /*
3590  * Parse command-line options.
3591  */
3593 
3594  /* Must have gotten a database name, or have a default (the username) */
3595  if (dbname == NULL)
3596  {
3597  dbname = username;
3598  if (dbname == NULL)
3599  ereport(FATAL,
3600  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3601  errmsg("%s: no database nor user name specified",
3602  progname)));
3603  }
3604 
3605  /* Acquire configuration parameters, unless inherited from postmaster */
3606  if (!IsUnderPostmaster)
3607  {
3609  proc_exit(1);
3610  }
3611 
3612  /*
3613  * Set up signal handlers and masks.
3614  *
3615  * Note that postmaster blocked all signals before forking child process,
3616  * so there is no race condition whereby we might receive a signal before
3617  * we have set up the handler.
3618  *
3619  * Also note: it's best not to use any signals that are SIG_IGNored in the
3620  * postmaster. If such a signal arrives before we are able to change the
3621  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3622  * handler in the postmaster to reserve the signal. (Of course, this isn't
3623  * an issue for signals that are locally generated, such as SIGALRM and
3624  * SIGPIPE.)
3625  */
3626  if (am_walsender)
3627  WalSndSignals();
3628  else
3629  {
3630  pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3631  * file */
3632  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3633  pqsignal(SIGTERM, die); /* cancel current query and exit */
3634 
3635  /*
3636  * In a standalone backend, SIGQUIT can be generated from the keyboard
3637  * easily, while SIGTERM cannot, so we make both signals do die()
3638  * rather than quickdie().
3639  */
3640  if (IsUnderPostmaster)
3641  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3642  else
3643  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3644  InitializeTimeouts(); /* establishes SIGALRM handler */
3645 
3646  /*
3647  * Ignore failure to write to frontend. Note: if frontend closes
3648  * connection, we will notice it and exit cleanly when control next
3649  * returns to outer loop. This seems safer than forcing exit in the
3650  * midst of output during who-knows-what operation...
3651  */
3656 
3657  /*
3658  * Reset some signals that are accepted by postmaster but not by
3659  * backend
3660  */
3661  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3662  * platforms */
3663  }
3664 
3665  pqinitmask();
3666 
3667  if (IsUnderPostmaster)
3668  {
3669  /* We allow SIGQUIT (quickdie) at all times */
3670  sigdelset(&BlockSig, SIGQUIT);
3671  }
3672 
3673  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3674 
3675  if (!IsUnderPostmaster)
3676  {
3677  /*
3678  * Validate we have been given a reasonable-looking DataDir (if under
3679  * postmaster, assume postmaster did this already).
3680  */
3681  Assert(DataDir);
3683 
3684  /* Change into DataDir (if under postmaster, was done already) */
3685  ChangeToDataDir();
3686 
3687  /*
3688  * Create lockfile for data directory.
3689  */
3690  CreateDataDirLockFile(false);
3691 
3692  /* Initialize MaxBackends (if under postmaster, was done already) */
3694  }
3695 
3696  /* Early initialization */
3697  BaseInit();
3698 
3699  /*
3700  * Create a per-backend PGPROC struct in shared memory, except in the
3701  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3702  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3703  * had to do some stuff with LWLocks).
3704  */
3705 #ifdef EXEC_BACKEND
3706  if (!IsUnderPostmaster)
3707  InitProcess();
3708 #else
3709  InitProcess();
3710 #endif
3711 
3712  /* We need to allow SIGINT, etc during the initial transaction */
3714 
3715  /*
3716  * General initialization.
3717  *
3718  * NOTE: if you are tempted to add code in this vicinity, consider putting
3719  * it inside InitPostgres() instead. In particular, anything that
3720  * involves database access should be there, not here.
3721  */
3723 
3724  /*
3725  * If the PostmasterContext is still around, recycle the space; we don't
3726  * need it anymore after InitPostgres completes. Note this does not trash
3727  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3728  * ... else we'd need to copy the Port data first. Also, subsidiary data
3729  * such as the username isn't lost either; see ProcessStartupPacket().
3730  */
3731  if (PostmasterContext)
3732  {
3735  }
3736 
3738 
3739  /*
3740  * Now all GUC states are fully set up. Report them to client if
3741  * appropriate.
3742  */
3744 
3745  /*
3746  * Also set up handler to log session end; we have to wait till now to be
3747  * sure Log_disconnections has its final value.
3748  */
3751 
3752  /* Perform initialization specific to a WAL sender process. */
3753  if (am_walsender)
3754  InitWalSender();
3755 
3756  /*
3757  * process any libraries that should be preloaded at backend start (this
3758  * likewise can't be done until GUC settings are complete)
3759  */
3761 
3762  /*
3763  * Send this backend's cancellation info to the frontend.
3764  */
3766  {
3768 
3769  pq_beginmessage(&buf, 'K');
3770  pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3771  pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3772  pq_endmessage(&buf);
3773  /* Need not flush since ReadyForQuery will do it. */
3774  }
3775 
3776  /* Welcome banner for standalone case */
3778  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3779 
3780  /*
3781  * Create the memory context we will use in the main loop.
3782  *
3783  * MessageContext is reset once per iteration of the main loop, ie, upon
3784  * completion of processing of each command message from the client.
3785  */
3787  "MessageContext",
3789 
3790  /*
3791  * Remember stand-alone backend startup time
3792  */
3793  if (!IsUnderPostmaster)
3795 
3796  /*
3797  * POSTGRES main processing loop begins here
3798  *
3799  * If an exception is encountered, processing resumes here so we abort the
3800  * current transaction and start a new one.
3801  *
3802  * You might wonder why this isn't coded as an infinite loop around a
3803  * PG_TRY construct. The reason is that this is the bottom of the
3804  * exception stack, and so with PG_TRY there would be no exception handler
3805  * in force at all during the CATCH part. By leaving the outermost setjmp
3806  * always active, we have at least some chance of recovering from an error
3807  * during error recovery. (If we get into an infinite loop thereby, it
3808  * will soon be stopped by overflow of elog.c's internal state stack.)
3809  *
3810  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3811  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3812  * is essential in case we longjmp'd out of a signal handler on a platform
3813  * where that leaves the signal blocked. It's not redundant with the
3814  * unblock in AbortTransaction() because the latter is only called if we
3815  * were inside a transaction.
3816  */
3817 
3818  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3819  {
3820  /*
3821  * NOTE: if you are tempted to add more code in this if-block,
3822  * consider the high probability that it should be in
3823  * AbortTransaction() instead. The only stuff done directly here
3824  * should be stuff that is guaranteed to apply *only* for outer-level
3825  * error recovery, such as adjusting the FE/BE protocol status.
3826  */
3827 
3828  /* Since not using PG_TRY, must reset error stack by hand */
3830 
3831  /* Prevent interrupts while cleaning up */
3832  HOLD_INTERRUPTS();
3833 
3834  /*
3835  * Forget any pending QueryCancel request, since we're returning to
3836  * the idle loop anyway, and cancel any active timeout requests. (In
3837  * future we might want to allow some timeout requests to survive, but
3838  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3839  * we got here because of a query cancel interrupting the SIGALRM
3840  * interrupt handler.) Note in particular that we must clear the
3841  * statement and lock timeout indicators, to prevent any future plain
3842  * query cancels from being misreported as timeouts in case we're
3843  * forgetting a timeout cancel.
3844  */
3845  disable_all_timeouts(false);
3846  QueryCancelPending = false; /* second to avoid race condition */
3847 
3848  /* Not reading from the client anymore. */
3849  DoingCommandRead = false;
3850 
3851  /* Make sure libpq is in a good state */
3852  pq_comm_reset();
3853 
3854  /* Report the error to the client and/or server log */
3855  EmitErrorReport();
3856 
3857  /*
3858  * Make sure debug_query_string gets reset before we possibly clobber
3859  * the storage it points at.
3860  */
3862 
3863  /*
3864  * Abort the current transaction in order to recover.
3865  */
3867 
3868  if (am_walsender)
3870 
3871  /*
3872  * We can't release replication slots inside AbortTransaction() as we
3873  * need to be able to start and abort transactions while having a slot
3874  * acquired. But we never need to hold them across top level errors,
3875  * so releasing here is fine. There's another cleanup in ProcKill()
3876  * ensuring we'll correctly cleanup on FATAL errors as well.
3877  */
3878  if (MyReplicationSlot != NULL)
3880 
3881  /* We also want to cleanup temporary slots on error. */
3883 
3884  /*
3885  * Now return to normal top-level context and clear ErrorContext for
3886  * next time.
3887  */
3889  FlushErrorState();
3890 
3891  /*
3892  * If we were handling an extended-query-protocol message, initiate
3893  * skip till next Sync. This also causes us not to issue
3894  * ReadyForQuery (until we get Sync).
3895  */
3897  ignore_till_sync = true;
3898 
3899  /* We don't have a transaction command open anymore */
3900  xact_started = false;
3901 
3902  /*
3903  * If an error occurred while we were reading a message from the
3904  * client, we have potentially lost track of where the previous
3905  * message ends and the next one begins. Even though we have
3906  * otherwise recovered from the error, we cannot safely read any more
3907  * messages from the client, so there isn't much we can do with the
3908  * connection anymore.
3909  */
3910  if (pq_is_reading_msg())
3911  ereport(FATAL,
3912  (errcode(ERRCODE_PROTOCOL_VIOLATION),
3913  errmsg("terminating connection because protocol synchronization was lost")));
3914 
3915  /* Now we can allow interrupts again */
3917  }
3918 
3919  /* We can now handle ereport(ERROR) */
3920  PG_exception_stack = &local_sigjmp_buf;
3921 
3922  if (!ignore_till_sync)
3923  send_ready_for_query = true; /* initially, or after error */
3924 
3925  /*
3926  * Non-error queries loop here.
3927  */
3928 
3929  for (;;)
3930  {
3931  /*
3932  * At top of loop, reset extended-query-message flag, so that any
3933  * errors encountered in "idle" state don't provoke skip.
3934  */
3936 
3937  /*
3938  * Release storage left over from prior query cycle, and create a new
3939  * query input buffer in the cleared MessageContext.
3940  */
3943 
3944  initStringInfo(&input_message);
3945 
3946  /*
3947  * Also consider releasing our catalog snapshot if any, so that it's
3948  * not preventing advance of global xmin while we wait for the client.
3949  */
3951 
3952  /*
3953  * (1) If we've reached idle state, tell the frontend we're ready for
3954  * a new query.
3955  *
3956  * Note: this includes fflush()'ing the last of the prior output.
3957  *
3958  * This is also a good time to send collected statistics to the
3959  * collector, and to update the PS stats display. We avoid doing
3960  * those every time through the message loop because it'd slow down
3961  * processing of batched messages, and because we don't want to report
3962  * uncommitted updates (that confuses autovacuum). The notification
3963  * processor wants a call too, if we are not in a transaction block.
3964  */
3965  if (send_ready_for_query)
3966  {
3968  {
3969  set_ps_display("idle in transaction (aborted)", false);
3971 
3972  /* Start the idle-in-transaction timer */
3974  {
3975  disable_idle_in_transaction_timeout = true;
3978  }
3979  }
3981  {
3982  set_ps_display("idle in transaction", false);
3984 
3985  /* Start the idle-in-transaction timer */
3987  {
3988  disable_idle_in_transaction_timeout = true;
3991  }
3992  }
3993  else
3994  {
3996  pgstat_report_stat(false);
3997 
3998  set_ps_display("idle", false);
4000  }
4001 
4003  send_ready_for_query = false;
4004  }
4005 
4006  /*
4007  * (2) Allow asynchronous signals to be executed immediately if they
4008  * come in while we are waiting for client input. (This must be
4009  * conditional since we don't want, say, reads on behalf of COPY FROM
4010  * STDIN doing the same thing.)
4011  */
4012  DoingCommandRead = true;
4013 
4014  /*
4015  * (3) read a command (loop blocks here)
4016  */
4017  firstchar = ReadCommand(&input_message);
4018 
4019  /*
4020  * (4) disable async signal conditions again.
4021  *
4022  * Query cancel is supposed to be a no-op when there is no query in
4023  * progress, so if a query cancel arrived while we were idle, just
4024  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4025  * it's called when DoingCommandRead is set, so check for interrupts
4026  * before resetting DoingCommandRead.
4027  */
4029  DoingCommandRead = false;
4030 
4031  /*
4032  * (5) turn off the idle-in-transaction timeout
4033  */
4034  if (disable_idle_in_transaction_timeout)
4035  {
4037  disable_idle_in_transaction_timeout = false;
4038  }
4039 
4040  /*
4041  * (6) check for any other interesting events that happened while we
4042  * slept.
4043  */
4044  if (got_SIGHUP)
4045  {
4046  got_SIGHUP = false;
4048  }
4049 
4050  /*
4051  * (7) process the command. But ignore it if we're skipping till
4052  * Sync.
4053  */
4054  if (ignore_till_sync && firstchar != EOF)
4055  continue;
4056 
4057  switch (firstchar)
4058  {
4059  case 'Q': /* simple query */
4060  {
4061  const char *query_string;
4062 
4063  /* Set statement_timestamp() */
4065 
4066  query_string = pq_getmsgstring(&input_message);
4067  pq_getmsgend(&input_message);
4068 
4069  if (am_walsender)
4070  {
4071  if (!exec_replication_command(query_string))
4072  exec_simple_query(query_string);
4073  }
4074  else
4075  exec_simple_query(query_string);
4076 
4077  send_ready_for_query = true;
4078  }
4079  break;
4080 
4081  case 'P': /* parse */
4082  {
4083  const char *stmt_name;
4084  const char *query_string;
4085  int numParams;
4086  Oid *paramTypes = NULL;
4087 
4088  forbidden_in_wal_sender(firstchar);
4089 
4090  /* Set statement_timestamp() */
4092 
4093  stmt_name = pq_getmsgstring(&input_message);
4094  query_string = pq_getmsgstring(&input_message);
4095  numParams = pq_getmsgint(&input_message, 2);
4096  if (numParams > 0)
4097  {
4098  int i;
4099 
4100  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4101  for (i = 0; i < numParams; i++)
4102  paramTypes[i] = pq_getmsgint(&input_message, 4);
4103  }
4104  pq_getmsgend(&input_message);
4105 
4106  exec_parse_message(query_string, stmt_name,
4107  paramTypes, numParams);
4108  }
4109  break;
4110 
4111  case 'B': /* bind */
4112  forbidden_in_wal_sender(firstchar);
4113 
4114  /* Set statement_timestamp() */
4116 
4117  /*
4118  * this message is complex enough that it seems best to put
4119  * the field extraction out-of-line
4120  */
4121  exec_bind_message(&input_message);
4122  break;
4123 
4124  case 'E': /* execute */
4125  {
4126  const char *portal_name;
4127  int max_rows;
4128 
4129  forbidden_in_wal_sender(firstchar);
4130 
4131  /* Set statement_timestamp() */
4133 
4134  portal_name = pq_getmsgstring(&input_message);
4135  max_rows = pq_getmsgint(&input_message, 4);
4136  pq_getmsgend(&input_message);
4137 
4138  exec_execute_message(portal_name, max_rows);
4139  }
4140  break;
4141 
4142  case 'F': /* fastpath function call */
4143  forbidden_in_wal_sender(firstchar);
4144 
4145  /* Set statement_timestamp() */
4147 
4148  /* Report query to various monitoring facilities. */
4150  set_ps_display("<FASTPATH>", false);
4151 
4152  /* start an xact for this function invocation */
4154 
4155  /*
4156  * Note: we may at this point be inside an aborted
4157  * transaction. We can't throw error for that until we've
4158  * finished reading the function-call message, so
4159  * HandleFunctionRequest() must check for it after doing so.
4160  * Be careful not to do anything that assumes we're inside a
4161  * valid transaction here.
4162  */
4163 
4164  /* switch back to message context */
4166 
4167  HandleFunctionRequest(&input_message);
4168 
4169  /* commit the function-invocation transaction */
4171 
4172  send_ready_for_query = true;
4173  break;
4174 
4175  case 'C': /* close */
4176  {
4177  int close_type;
4178  const char *close_target;
4179 
4180  forbidden_in_wal_sender(firstchar);
4181 
4182  close_type = pq_getmsgbyte(&input_message);
4183  close_target = pq_getmsgstring(&input_message);
4184  pq_getmsgend(&input_message);
4185 
4186  switch (close_type)
4187  {
4188  case 'S':
4189  if (close_target[0] != '\0')
4190  DropPreparedStatement(close_target, false);
4191  else
4192  {
4193  /* special-case the unnamed statement */
4195  }
4196  break;
4197  case 'P':
4198  {
4199  Portal portal;
4200 
4201  portal = GetPortalByName(close_target);
4202  if (PortalIsValid(portal))
4203  PortalDrop(portal, false);
4204  }
4205  break;
4206  default:
4207  ereport(ERROR,
4208  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4209  errmsg("invalid CLOSE message subtype %d",
4210  close_type)));
4211  break;
4212  }
4213 
4215  pq_putemptymessage('3'); /* CloseComplete */
4216  }
4217  break;
4218 
4219  case 'D': /* describe */
4220  {
4221  int describe_type;
4222  const char *describe_target;
4223 
4224  forbidden_in_wal_sender(firstchar);
4225 
4226  /* Set statement_timestamp() (needed for xact) */
4228 
4229  describe_type = pq_getmsgbyte(&input_message);
4230  describe_target = pq_getmsgstring(&input_message);
4231  pq_getmsgend(&input_message);
4232 
4233  switch (describe_type)
4234  {
4235  case 'S':
4236  exec_describe_statement_message(describe_target);
4237  break;
4238  case 'P':
4239  exec_describe_portal_message(describe_target);
4240  break;
4241  default:
4242  ereport(ERROR,
4243  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4244  errmsg("invalid DESCRIBE message subtype %d",
4245  describe_type)));
4246  break;
4247  }
4248  }
4249  break;
4250 
4251  case 'H': /* flush */
4252  pq_getmsgend(&input_message);
4254  pq_flush();
4255  break;
4256 
4257  case 'S': /* sync */
4258  pq_getmsgend(&input_message);
4260  send_ready_for_query = true;
4261  break;
4262 
4263  /*
4264  * 'X' means that the frontend is closing down the socket. EOF
4265  * means unexpected loss of frontend connection. Either way,
4266  * perform normal shutdown.
4267  */
4268  case 'X':
4269  case EOF:
4270 
4271  /*
4272  * Reset whereToSendOutput to prevent ereport from attempting
4273  * to send any more messages to client.
4274  */
4277 
4278  /*
4279  * NOTE: if you are tempted to add more code here, DON'T!
4280  * Whatever you had in mind to do should be set up as an
4281  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4282  * it will fail to be called during other backend-shutdown
4283  * scenarios.
4284  */
4285  proc_exit(0);
4286 
4287  case 'd': /* copy data */
4288  case 'c': /* copy done */
4289  case 'f': /* copy fail */
4290 
4291  /*
4292  * Accept but ignore these messages, per protocol spec; we
4293  * probably got here because a COPY failed, and the frontend
4294  * is still sending data.
4295  */
4296  break;
4297 
4298  default:
4299  ereport(FATAL,
4300  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4301  errmsg("invalid frontend message type %d",
4302  firstchar)));
4303  }
4304  } /* end of input-reading loop */
4305 }
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:2389
#define SIGUSR1
Definition: win32.h:202
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
void BeginReportingGUCOptions(void)
Definition: guc.c:5364
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:2458
void ProcessConfigFile(GucContext context)
bool exec_replication_command(const char *cmd_string)
Definition: walsender.c:1364
static volatile sig_atomic_t got_SIGHUP
Definition: postgres.c:129
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
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:2958
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:4315
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 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:189
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:2654
signed int int32
Definition: c.h:256
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1846
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4475
#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:185
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:2862
#define FATAL
Definition: elog.h:52
static void SigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2688
#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:66
bool IsUnderPostmaster
Definition: globals.c:100
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1463
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:1201
#define PortalIsValid(p)
Definition: portal.h:199
static void start_xact_command(void)
Definition: postgres.c:2440
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:284
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:4693
void EmitErrorReport(void)
Definition: elog.c:1446
TimestampTz PgStartTime
Definition: timestamp.c:49
#define SIGPIPE
Definition: win32.h:193
#define SIGHUP
Definition: win32.h:188
static char * username
Definition: initdb.c:131
#define InvalidOid
Definition: postgres_ext.h:36
#define SIG_DFL
Definition: win32.h:183
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 HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:261
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:2623
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2675
static void drop_unnamed_stmt(void)
Definition: postgres.c:2537
char * DataDir
Definition: globals.c:59
void ReplicationSlotCleanup(void)
Definition: slot.c:413
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:3308
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:198
static bool ignore_till_sync
Definition: postgres.c:149
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2562
MemoryContext PostmasterContext
Definition: mcxt.c:45
#define SIGUSR2
Definition: win32.h:203
static void exec_simple_query(const char *query_string)
Definition: postgres.c:884
void InitializeGUCOptions(void)
Definition: guc.c:4471
void pgstat_report_stat(bool force)
Definition: pgstat.c:780
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:2296
void process_postgres_switches ( int  argc,
char *  argv[],
GucContext  ctx,
const char **  dbname 
)

Definition at line 3308 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().

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

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

2706 {
2707  int save_errno = errno;
2708 
2709  /*
2710  * Don't joggle the elbow of proc_exit
2711  */
2712  if (!proc_exit_inprogress)
2713  {
2714  RecoveryConflictReason = reason;
2715  switch (reason)
2716  {
2718 
2719  /*
2720  * If we aren't waiting for a lock we can never deadlock.
2721  */
2722  if (!IsWaitingForLock())
2723  return;
2724 
2725  /* Intentional drop through to check wait for pin */
2726 
2728 
2729  /*
2730  * If we aren't blocking the Startup process there is nothing
2731  * more to do.
2732  */
2734  return;
2735 
2737 
2738  /* Intentional drop through to error handling */
2739 
2743 
2744  /*
2745  * If we aren't in a transaction any longer then ignore.
2746  */
2748  return;
2749 
2750  /*
2751  * If we can abort just the current subtransaction then we are
2752  * OK to throw an ERROR to resolve the conflict. Otherwise
2753  * drop through to the FATAL case.
2754  *
2755  * XXX other times that we can throw just an ERROR *may* be
2756  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2757  * parent transactions
2758  *
2759  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2760  * by parent transactions and the transaction is not
2761  * transaction-snapshot mode
2762  *
2763  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2764  * cursors open in parent transactions
2765  */
2766  if (!IsSubTransaction())
2767  {
2768  /*
2769  * If we already aborted then we no longer need to cancel.
2770  * We do this here since we do not wish to ignore aborted
2771  * subtransactions, which must cause FATAL, currently.
2772  */
2774  return;
2775 
2776  RecoveryConflictPending = true;
2777  QueryCancelPending = true;
2778  InterruptPending = true;
2779  break;
2780  }
2781 
2782  /* Intentional drop through to session cancel */
2783 
2785  RecoveryConflictPending = true;
2786  ProcDiePending = true;
2787  InterruptPending = true;
2788  break;
2789 
2790  default:
2791  elog(FATAL, "unrecognized conflict mode: %d",
2792  (int) reason);
2793  }
2794 
2796 
2797  /*
2798  * All conflicts apart from database cause dynamic errors where the
2799  * command or transaction can be retried at a later point with some
2800  * potential for success. No need to reset this, since non-retryable
2801  * conflict errors are currently FATAL.
2802  */
2803  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2804  RecoveryConflictRetryable = false;
2805  }
2806 
2807  /*
2808  * Set the process latch. This function essentially emulates signal
2809  * handlers like die() and StatementCancelHandler() and it seems prudent
2810  * to behave similarly as they do.
2811  */
2812  SetLatch(MyLatch);
2813 
2814  errno = save_errno;
2815 }
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:123
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:367
#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 4373 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().

4374 {
4377 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4369
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4370
#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 3197 of file postgres.c.

References PGC_POSTMASTER, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

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

Definition at line 3226 of file postgres.c.

References NULL, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

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

Definition at line 4380 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().

4381 {
4382  StringInfoData str;
4383  struct timeval user,
4384  sys;
4385  struct timeval elapse_t;
4386  struct rusage r;
4387 
4388  getrusage(RUSAGE_SELF, &r);
4389  gettimeofday(&elapse_t, NULL);
4390  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4391  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4392  if (elapse_t.tv_usec < Save_t.tv_usec)
4393  {
4394  elapse_t.tv_sec--;
4395  elapse_t.tv_usec += 1000000;
4396  }
4397  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4398  {
4399  r.ru_utime.tv_sec--;
4400  r.ru_utime.tv_usec += 1000000;
4401  }
4402  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4403  {
4404  r.ru_stime.tv_sec--;
4405  r.ru_stime.tv_usec += 1000000;
4406  }
4407 
4408  /*
4409  * the only stats we don't show here are for memory usage -- i can't
4410  * figure out how to interpret the relevant fields in the rusage struct,
4411  * and they change names across o/s platforms, anyway. if you can figure
4412  * out what the entries mean, you can somehow extract resident set size,
4413  * shared text size, and unshared data and stack sizes.
4414  */
4415  initStringInfo(&str);
4416 
4417  appendStringInfoString(&str, "! system usage stats:\n");
4418  appendStringInfo(&str,
4419  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4420  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4421  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4422  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4423  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4424  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4425  (long) (elapse_t.tv_usec - Save_t.tv_usec));
4426  appendStringInfo(&str,
4427  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4428  (long) user.tv_sec,
4429  (long) user.tv_usec,
4430  (long) sys.tv_sec,
4431  (long) sys.tv_usec);
4432 #if defined(HAVE_GETRUSAGE)
4433  appendStringInfo(&str,
4434  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4435  r.ru_inblock - Save_r.ru_inblock,
4436  /* they only drink coffee at dec */
4437  r.ru_oublock - Save_r.ru_oublock,
4438  r.ru_inblock, r.ru_oublock);
4439  appendStringInfo(&str,
4440  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4441  r.ru_majflt - Save_r.ru_majflt,
4442  r.ru_minflt - Save_r.ru_minflt,
4443  r.ru_majflt, r.ru_minflt,
4444  r.ru_nswap - Save_r.ru_nswap,
4445  r.ru_nswap);
4446  appendStringInfo(&str,
4447  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4448  r.ru_nsignals - Save_r.ru_nsignals,
4449  r.ru_nsignals,
4450  r.ru_msgrcv - Save_r.ru_msgrcv,
4451  r.ru_msgsnd - Save_r.ru_msgsnd,
4452  r.ru_msgrcv, r.ru_msgsnd);
4453  appendStringInfo(&str,
4454  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4455  r.ru_nvcsw - Save_r.ru_nvcsw,
4456  r.ru_nivcsw - Save_r.ru_nivcsw,
4457  r.ru_nvcsw, r.ru_nivcsw);
4458 #endif /* HAVE_GETRUSAGE */
4459 
4460  /* remove trailing newline */
4461  if (str.data[str.len - 1] == '\n')
4462  str.data[--str.len] = '\0';
4463 
4464  ereport(LOG,
4465  (errmsg_internal("%s", title),
4466  errdetail_internal("%s", str.data)));
4467 
4468  pfree(str.data);
4469 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4369
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:4370
#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 2654 of file postgres.c.

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

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

2655 {
2656  int save_errno = errno;
2657 
2658  /*
2659  * Don't joggle the elbow of proc_exit
2660  */
2661  if (!proc_exit_inprogress)
2662  {
2663  InterruptPending = true;
2664  QueryCancelPending = true;
2665  }
2666 
2667  /* If we're still here, waken anything waiting on the process latch */
2668  SetLatch(MyLatch);
2669 
2670  errno = save_errno;
2671 }
volatile bool QueryCancelPending
Definition: globals.c:30
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:367
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