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 3197 of file postgres.c.

References max_stack_depth_bytes.

3198 {
3199  long newval_bytes = newval * 1024L;
3200 
3201  max_stack_depth_bytes = newval_bytes;
3202 }
static long max_stack_depth_bytes
Definition: postgres.c:109
#define newval
int check_log_duration ( char *  msec_str,
bool  was_logged 
)

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

2101 {
2103  {
2104  long secs;
2105  int usecs;
2106  int msecs;
2107  bool exceeded;
2108 
2111  &secs, &usecs);
2112  msecs = usecs / 1000;
2113 
2114  /*
2115  * This odd-looking test for log_min_duration_statement being exceeded
2116  * is designed to avoid integer overflow with very long durations:
2117  * don't compute secs * 1000 until we've verified it will fit in int.
2118  */
2119  exceeded = (log_min_duration_statement == 0 ||
2121  (secs > log_min_duration_statement / 1000 ||
2122  secs * 1000 + msecs >= log_min_duration_statement)));
2123 
2124  if (exceeded || log_duration)
2125  {
2126  snprintf(msec_str, 32, "%ld.%03d",
2127  secs * 1000 + msecs, usecs % 1000);
2128  if (exceeded && !was_logged)
2129  return 2;
2130  else
2131  return 1;
2132  }
2133  }
2134 
2135  return 0;
2136 }
int log_min_duration_statement
Definition: guc.c:453
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:432
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 3180 of file postgres.c.

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

3181 {
3182  long newval_bytes = *newval * 1024L;
3183  long stack_rlimit = get_stack_depth_rlimit();
3184 
3185  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3186  {
3187  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3188  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3189  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3190  return false;
3191  }
3192  return true;
3193 }
#define GUC_check_errdetail
Definition: guc.h:407
long get_stack_depth_rlimit(void)
Definition: postgres.c:4352
#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 2617 of file postgres.c.

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

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

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

Definition at line 2669 of file postgres.c.

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

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

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

References val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

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

Definition at line 3283 of file postgres.c.

References NULL, and optarg.

Referenced by PostmasterMain(), and process_postgres_switches().

3284 {
3285  switch (arg[0])
3286  {
3287  case 'p':
3288  if (optarg[1] == 'a') /* "parser" */
3289  return "log_parser_stats";
3290  else if (optarg[1] == 'l') /* "planner" */
3291  return "log_planner_stats";
3292  break;
3293 
3294  case 'e': /* "executor" */
3295  return "log_executor_stats";
3296  break;
3297  }
3298 
3299  return NULL;
3300 }
#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 638 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().

641 {
642  Query *query;
643  List *querytree_list;
644 
645  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
646 
647  /*
648  * (1) Perform parse analysis.
649  */
650  if (log_parser_stats)
651  ResetUsage();
652 
653  query = parse_analyze(parsetree, query_string, paramTypes, numParams,
654  queryEnv);
655 
656  if (log_parser_stats)
657  ShowUsage("PARSE ANALYSIS STATISTICS");
658 
659  /*
660  * (2) Rewrite the queries, as necessary
661  */
662  querytree_list = pg_rewrite_query(query);
663 
664  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
665 
666  return querytree_list;
667 }
bool log_parser_stats
Definition: guc.c:438
void ShowUsage(const char *title)
Definition: postgres.c:4395
void ResetUsage(void)
Definition: postgres.c:4388
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:727
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 675 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().

680 {
681  ParseState *pstate;
682  Query *query;
683  List *querytree_list;
684 
685  Assert(query_string != NULL); /* required as of 8.4 */
686 
687  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
688 
689  /*
690  * (1) Perform parse analysis.
691  */
692  if (log_parser_stats)
693  ResetUsage();
694 
695  pstate = make_parsestate(NULL);
696  pstate->p_sourcetext = query_string;
697  pstate->p_queryEnv = queryEnv;
698  (*parserSetup) (pstate, parserSetupArg);
699 
700  query = transformTopLevelStmt(pstate, parsetree);
701 
703  (*post_parse_analyze_hook) (pstate, query);
704 
705  free_parsestate(pstate);
706 
707  if (log_parser_stats)
708  ShowUsage("PARSE ANALYSIS STATISTICS");
709 
710  /*
711  * (2) Rewrite the queries, as necessary
712  */
713  querytree_list = pg_rewrite_query(query);
714 
715  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
716 
717  return querytree_list;
718 }
bool log_parser_stats
Definition: guc.c:438
QueryEnvironment * p_queryEnv
Definition: parse_node.h:195
void ShowUsage(const char *title)
Definition: postgres.c:4395
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void ResetUsage(void)
Definition: postgres.c:4388
const char * p_sourcetext
Definition: parse_node.h:171
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:727
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
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 596 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().

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

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

841 {
842  List *stmt_list = NIL;
843  ListCell *query_list;
844 
845  foreach(query_list, querytrees)
846  {
847  Query *query = lfirst_node(Query, query_list);
848  PlannedStmt *stmt;
849 
850  if (query->commandType == CMD_UTILITY)
851  {
852  /* Utility commands require no planning. */
853  stmt = makeNode(PlannedStmt);
854  stmt->commandType = CMD_UTILITY;
855  stmt->canSetTag = query->canSetTag;
856  stmt->utilityStmt = query->utilityStmt;
857  stmt->stmt_location = query->stmt_location;
858  stmt->stmt_len = query->stmt_len;
859  }
860  else
861  {
862  stmt = pg_plan_query(query, cursorOptions, boundParams);
863  }
864 
865  stmt_list = lappend(stmt_list, stmt);
866  }
867 
868  return stmt_list;
869 }
#define NIL
Definition: pg_list.h:69
int stmt_location
Definition: parsenodes.h:179
Node * utilityStmt
Definition: parsenodes.h:118
int stmt_len
Definition: plannodes.h:98
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int stmt_location
Definition: plannodes.h:97
Node * utilityStmt
Definition: plannodes.h:94
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:180
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:779
PlannedStmt* pg_plan_query ( Query querytree,
int  cursorOptions,
ParamListInfo  boundParams 
)

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

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

Definition at line 3582 of file postgres.c.

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), am_walsender, Assert, BaseInit(), BeginReportingGUCOptions(), BlockSig, buf, ChangeToDataDir(), CHECK_FOR_INTERRUPTS, ConfigReloadPending, 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(), 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, PostgresSigHupHandler(), 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, 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().

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

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

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

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

Referenced by interactive_getc(), and secure_read().

517 {
518  int save_errno = errno;
519 
520  if (DoingCommandRead)
521  {
522  /* Check for general interrupts that arrived while reading */
524 
525  /* Process sinval catchup interrupts that happened while reading */
528 
529  /* Process sinval catchup interrupts that happened while reading */
532  }
533  else if (ProcDiePending && blocked)
534  {
535  /*
536  * We're dying. It's safe (and sane) to handle that now.
537  */
539  }
540 
541  errno = save_errno;
542 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void ProcessNotifyInterrupt(void)
Definition: async.c:1726
static bool DoingCommandRead
Definition: postgres.c:137
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:98
void ProcessClientWriteInterrupt ( bool  blocked)

Definition at line 554 of file postgres.c.

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

Referenced by secure_write().

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

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

2557 {
2558  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2559  PG_SETMASK(&BlockSig);
2560 
2561  /*
2562  * Prevent interrupts while exiting; though we just blocked signals that
2563  * would queue new interrupts, one may have been pending. We don't want a
2564  * quickdie() downgraded to a mere query cancel.
2565  */
2566  HOLD_INTERRUPTS();
2567 
2568  /*
2569  * If we're aborting out of client auth, don't risk trying to send
2570  * anything to the client; we will likely violate the protocol, not to
2571  * mention that we may have interrupted the guts of OpenSSL or some
2572  * authentication library.
2573  */
2576 
2577  /*
2578  * Ideally this should be ereport(FATAL), but then we'd not get control
2579  * back...
2580  */
2581  ereport(WARNING,
2582  (errcode(ERRCODE_CRASH_SHUTDOWN),
2583  errmsg("terminating connection because of crash of another server process"),
2584  errdetail("The postmaster has commanded this server process to roll back"
2585  " the current transaction and exit, because another"
2586  " server process exited abnormally and possibly corrupted"
2587  " shared memory."),
2588  errhint("In a moment you should be able to reconnect to the"
2589  " database and repeat your command.")));
2590 
2591  /*
2592  * We DO NOT want to run proc_exit() callbacks -- we're here because
2593  * shared memory may be corrupted, so we don't want to try to clean up our
2594  * transaction. Just nail the windows shut and get out of town. Now that
2595  * there's an atexit callback to prevent third-party code from breaking
2596  * things by calling exit() directly, we have to reset the callbacks
2597  * explicitly to make this work as intended.
2598  */
2599  on_exit_reset();
2600 
2601  /*
2602  * Note we do exit(2) not exit(0). This is to force the postmaster into a
2603  * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2604  * backend. This is necessary precisely because we don't clean up our
2605  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2606  * should ensure the postmaster sees this as a crash, too, but no harm in
2607  * being doubly sure.)
2608  */
2609  exit(2);
2610 }
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:350
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:115
CommandDest whereToSendOutput
Definition: postgres.c:88
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:4346
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:161
static bool RecoveryConflictPending
Definition: postgres.c:159
static bool RecoveryConflictRetryable
Definition: postgres.c:160
volatile bool InterruptPending
Definition: globals.c:29
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:676
bool proc_exit_inprogress
Definition: ipc.c:40
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:3692
bool IsSubTransaction(void)
Definition: xact.c:4400
volatile bool ProcDiePending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:52
#define elog
Definition: elog.h:219
void ResetUsage ( void  )

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

4389 {
4392 }
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
static struct rusage Save_r
Definition: postgres.c:4384
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:31
static struct timeval Save_t
Definition: postgres.c:4385
#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 3212 of file postgres.c.

References PGC_POSTMASTER, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3213 {
3214  if (debug_flag > 0)
3215  {
3216  char debugstr[64];
3217 
3218  sprintf(debugstr, "debug%d", debug_flag);
3219  SetConfigOption("log_min_messages", debugstr, context, source);
3220  }
3221  else
3222  SetConfigOption("log_min_messages", "notice", context, source);
3223 
3224  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3225  {
3226  SetConfigOption("log_connections", "true", context, source);
3227  SetConfigOption("log_disconnections", "true", context, source);
3228  }
3229  if (debug_flag >= 2)
3230  SetConfigOption("log_statement", "all", context, source);
3231  if (debug_flag >= 3)
3232  SetConfigOption("debug_print_parse", "true", context, source);
3233  if (debug_flag >= 4)
3234  SetConfigOption("debug_print_plan", "true", context, source);
3235  if (debug_flag >= 5)
3236  SetConfigOption("debug_print_rewritten", "true", context, source);
3237 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6683
bool set_plan_disabling_options ( const char *  arg,
GucContext  context,
GucSource  source 
)

Definition at line 3241 of file postgres.c.

References NULL, and SetConfigOption().

Referenced by PostmasterMain(), and process_postgres_switches().

3242 {
3243  const char *tmp = NULL;
3244 
3245  switch (arg[0])
3246  {
3247  case 's': /* seqscan */
3248  tmp = "enable_seqscan";
3249  break;
3250  case 'i': /* indexscan */
3251  tmp = "enable_indexscan";
3252  break;
3253  case 'o': /* indexonlyscan */
3254  tmp = "enable_indexonlyscan";
3255  break;
3256  case 'b': /* bitmapscan */
3257  tmp = "enable_bitmapscan";
3258  break;
3259  case 't': /* tidscan */
3260  tmp = "enable_tidscan";
3261  break;
3262  case 'n': /* nestloop */
3263  tmp = "enable_nestloop";
3264  break;
3265  case 'm': /* mergejoin */
3266  tmp = "enable_mergejoin";
3267  break;
3268  case 'h': /* hashjoin */
3269  tmp = "enable_hashjoin";
3270  break;
3271  }
3272  if (tmp)
3273  {
3274  SetConfigOption(tmp, "false", context, source);
3275  return true;
3276  }
3277  else
3278  return false;
3279 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6683
#define NULL
Definition: c.h:229
void * arg
void ShowUsage ( const char *  title)

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

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

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

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

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

Variable Documentation

int log_statement

Definition at line 93 of file postgres.c.

Referenced by check_log_statement(), and HandleFunctionRequest().

int max_stack_depth

Definition at line 96 of file postgres.c.

Referenced by check_stack_depth().

int PostAuthDelay