From a9f4a027a7c8705fb3ac038a3b65f64b87686946 Mon Sep 17 00:00:00 2001 From: Ian Barwick Date: Mon, 11 Sep 2017 11:14:13 +0900 Subject: [PATCH] pgindent run --- compat.c | 1 - compat.h | 6 +- configfile.c | 186 +++--- configfile.h | 70 +- controldata.c | 10 +- controldata.h | 8 +- dbutils.c | 1090 +++++++++++++++--------------- dbutils.h | 262 ++++---- dirutil.c | 25 +- dirutil.h | 12 +- errcode.h | 3 +- log.c | 39 +- log.h | 13 +- repmgr-action-bdr.c | 73 +- repmgr-action-bdr.h | 2 +- repmgr-action-cluster.c | 515 +++++++------- repmgr-action-cluster.h | 12 +- repmgr-action-node.c | 852 +++++++++++------------ repmgr-action-node.h | 2 +- repmgr-action-primary.c | 85 ++- repmgr-action-standby.c | 1410 +++++++++++++++++++++------------------ repmgr-action-standby.h | 2 +- repmgr-client-global.h | 28 +- repmgr-client.c | 985 ++++++++++++++------------- repmgr-client.h | 30 +- repmgr.c | 63 +- repmgr.h | 24 +- repmgrd-bdr.c | 204 +++--- repmgrd-bdr.h | 2 +- repmgrd-physical.c | 548 ++++++++------- repmgrd-physical.h | 10 +- repmgrd.c | 124 ++-- repmgrd.h | 16 +- strutil.c | 30 +- strutil.h | 64 +- voting.h | 5 +- 36 files changed, 3523 insertions(+), 3288 deletions(-) diff --git a/compat.c b/compat.c index e3d3ee31..2f56ced9 100644 --- a/compat.c +++ b/compat.c @@ -104,4 +104,3 @@ appendShellString(PQExpBuffer buf, const char *str) appendPQExpBufferChar(buf, '\''); } - diff --git a/compat.h b/compat.h index 5d355af8..e5984b17 100644 --- a/compat.h +++ b/compat.h @@ -23,10 +23,8 @@ #ifndef _COMPAT_H_ #define _COMPAT_H_ -extern void -appendConnStrVal(PQExpBuffer buf, const char *str); +extern void appendConnStrVal(PQExpBuffer buf, const char *str); -extern void -appendShellString(PQExpBuffer buf, const char *str); +extern void appendShellString(PQExpBuffer buf, const char *str); #endif diff --git a/configfile.c b/configfile.c index e8014c4d..3e5f8bb1 100644 --- a/configfile.c +++ b/configfile.c @@ -24,25 +24,25 @@ #include "log.h" const static char *_progname = NULL; -char config_file_path[MAXPGPATH] = ""; +char config_file_path[MAXPGPATH] = ""; static bool config_file_provided = false; -bool config_file_found = false; +bool config_file_found = false; -static void _parse_config(t_configuration_options *options, ItemList *error_list, ItemList *warning_list); -static bool parse_bool(const char *s, - const char *config_item, - ItemList *error_list); +static void _parse_config(t_configuration_options *options, ItemList *error_list, ItemList *warning_list); +static bool parse_bool(const char *s, + const char *config_item, + ItemList *error_list); -static void _parse_line(char *buf, char *name, char *value); -static void parse_event_notifications_list(t_configuration_options *options, const char *arg); +static void _parse_line(char *buf, char *name, char *value); +static void parse_event_notifications_list(t_configuration_options *options, const char *arg); static void clear_event_notification_list(t_configuration_options *options); static void parse_time_unit_parameter(const char *name, const char *value, char *dest, ItemList *errors); -static void tablespace_list_append(t_configuration_options *options, const char *arg); +static void tablespace_list_append(t_configuration_options *options, const char *arg); -static void exit_with_config_file_errors(ItemList *config_errors, ItemList *config_warnings, bool terse); +static void exit_with_config_file_errors(ItemList *config_errors, ItemList *config_warnings, bool terse); void @@ -63,10 +63,10 @@ load_config(const char *config_file, bool verbose, bool terse, t_configuration_o struct stat stat_config; /* - * If a configuration file was provided, check it exists, otherwise - * emit an error and terminate. We assume that if a user explicitly - * provides a configuration file, they'll want to make sure it's - * used and not fall back to any of the defaults. + * If a configuration file was provided, check it exists, otherwise emit + * an error and terminate. We assume that if a user explicitly provides a + * configuration file, they'll want to make sure it's used and not fall + * back to any of the defaults. */ if (config_file != NULL && config_file[0] != '\0') { @@ -76,8 +76,8 @@ load_config(const char *config_file, bool verbose, bool terse, t_configuration_o if (stat(config_file_path, &stat_config) != 0) { log_error(_("provided configuration file \"%s\" not found: %s"), - config_file, - strerror(errno) + config_file, + strerror(errno) ); exit(ERR_BAD_CONFIG); } @@ -92,18 +92,19 @@ load_config(const char *config_file, bool verbose, bool terse, t_configuration_o } - /* + /*----------- * If no configuration file was provided, attempt to find a default file * in this order: - * - current directory - * - /etc/repmgr.conf - * - default sysconfdir + * - current directory + * - /etc/repmgr.conf + * - default sysconfdir * - * here we just check for the existence of the file; parse_config() - * will handle read errors etc. + * here we just check for the existence of the file; parse_config() will + * handle read errors etc. * * XXX modify this section so package maintainers can provide a patch - * specifying location of a distribution-specific configuration file + * specifying location of a distribution-specific configuration file + *----------- */ if (config_file_provided == false) { @@ -159,7 +160,7 @@ load_config(const char *config_file, bool verbose, bool terse, t_configuration_o goto end_search; } - end_search: +end_search: if (config_file_found == true) { if (verbose == true) @@ -186,8 +187,8 @@ void parse_config(t_configuration_options *options, bool terse) { /* Collate configuration file errors here for friendlier reporting */ - static ItemList config_errors = { NULL, NULL }; - static ItemList config_warnings = { NULL, NULL }; + static ItemList config_errors = {NULL, NULL}; + static ItemList config_warnings = {NULL, NULL}; _parse_config(options, &config_errors, &config_warnings); @@ -273,7 +274,8 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * /* default to 6 reconnection attempts at intervals of 10 seconds */ options->reconnect_attempts = DEFAULT_RECONNECTION_ATTEMPTS; options->reconnect_interval = DEFAULT_RECONNECTION_INTERVAL; - options->monitoring_history = false; /* new in 4.0, replaces --monitoring-history */ + options->monitoring_history = false; /* new in 4.0, replaces + * --monitoring-history */ options->degraded_monitoring_timeout = -1; options->async_query_timeout = DEFAULT_ASYNC_QUERY_TIMEOUT; options->primary_notification_timeout = DEFAULT_PRIMARY_NOTIFICATION_TIMEOUT; @@ -326,16 +328,16 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * { log_verbose(LOG_NOTICE, _("no configuration file provided and no default file found - " - "continuing with default values")); + "continuing with default values")); return; } fp = fopen(config_file_path, "r"); /* - * A configuration file has been found, either provided by the user - * or found in one of the default locations. If we can't open it, - * fail with an error. + * A configuration file has been found, either provided by the user or + * found in one of the default locations. If we can't open it, fail with + * an error. */ if (fp == NULL) { @@ -347,7 +349,7 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * else { log_error(_("unable to open default configuration file \"%s\"; terminating"), - config_file_path); + config_file_path); } exit(ERR_BAD_CONFIG); @@ -356,7 +358,7 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * /* Read file */ while ((s = fgets(buf, sizeof buf, fp)) != NULL) { - bool known_parameter = true; + bool known_parameter = true; /* Parse name/value pair from line */ _parse_line(buf, name, value); @@ -387,7 +389,7 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * strncpy(options->replication_user, value, NAMEDATALEN); else item_list_append(error_list, - _( "value for \"replication_user\" must contain fewer than " STR(NAMEDATALEN) " characters")); + _("value for \"replication_user\" must contain fewer than " STR(NAMEDATALEN) " characters")); } else if (strcmp(name, "pg_bindir") == 0) strncpy(options->pg_bindir, value, MAXPGPATH); @@ -524,7 +526,10 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * else if (strcmp(name, "promote_delay") == 0) options->promote_delay = repmgr_atoi(value, name, error_list, 1); - /* Following parameters have been deprecated or renamed from 3.x - issue a warning */ + /* + * Following parameters have been deprecated or renamed from 3.x - + * issue a warning + */ else if (strcmp(name, "cluster") == 0) { item_list_append(warning_list, @@ -578,14 +583,18 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * known_parameter = false; log_warning(_("%s/%s: unknown name/value pair provided; ignoring"), name, value); } + /* - * Raise an error if a known parameter is provided with an empty value. - * Currently there's no reason why empty parameters are needed; if - * we want to accept those, we'd need to add stricter default checking, - * as currently e.g. an empty `node` value will be converted to '0'. + * Raise an error if a known parameter is provided with an empty + * value. Currently there's no reason why empty parameters are needed; + * if we want to accept those, we'd need to add stricter default + * checking, as currently e.g. an empty `node` value will be converted + * to '0'. */ - if (known_parameter == true && !strlen(value)) { - char error_message_buf[MAXLEN] = ""; + if (known_parameter == true && !strlen(value)) + { + char error_message_buf[MAXLEN] = ""; + maxlen_snprintf(error_message_buf, _("\"%s\": no value provided"), name); @@ -618,10 +627,11 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * } else { - /* Sanity check the provided conninfo string + /* + * Sanity check the provided conninfo string * - * NOTE: PQconninfoParse() verifies the string format and checks for valid options - * but does not sanity check values + * NOTE: PQconninfoParse() verifies the string format and checks for + * valid options but does not sanity check values */ PQconninfoOption *conninfo_options = NULL; @@ -630,7 +640,8 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * conninfo_options = PQconninfoParse(options->conninfo, &conninfo_errmsg); if (conninfo_options == NULL) { - char error_message_buf[MAXLEN] = ""; + char error_message_buf[MAXLEN] = ""; + snprintf(error_message_buf, MAXLEN, _("\"conninfo\": %s (provided: \"%s\")"), @@ -662,7 +673,7 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * _("\archive_ready_critical\" must be greater than \"archive_ready_warning\"")); } - if( options->replication_lag_warning >= options->replication_lag_critical) + if (options->replication_lag_warning >= options->replication_lag_critical) { item_list_append(error_list, _("\replication_lag_critical\" must be greater than \"replication_lag_warning\"")); @@ -675,7 +686,7 @@ _parse_config(t_configuration_options *options, ItemList *error_list, ItemList * bool parse_recovery_conf(const char *data_dir, t_recovery_conf *conf) { - char recovery_conf_path[MAXPGPATH] = ""; + char recovery_conf_path[MAXPGPATH] = ""; FILE *fp; char *s = NULL, buf[MAXLINELENGTH] = ""; @@ -780,9 +791,9 @@ _parse_line(char *buf, char *name, char *value) if (buf[i] == '=') break; - switch(buf[i]) + switch (buf[i]) { - /* Ignore whitespace */ + /* Ignore whitespace */ case ' ': case '\n': case '\r': @@ -799,9 +810,9 @@ _parse_line(char *buf, char *name, char *value) */ for (; i < MAXLEN; ++i) { - if (buf[i+1] == ' ') + if (buf[i + 1] == ' ') continue; - if (buf[i+1] == '\t') + if (buf[i + 1] == '\t') continue; break; @@ -828,17 +839,17 @@ _parse_line(char *buf, char *name, char *value) static void parse_time_unit_parameter(const char *name, const char *value, char *dest, ItemList *errors) { - char *ptr = NULL; - int targ = strtol(value, &ptr, 10); + char *ptr = NULL; + int targ = strtol(value, &ptr, 10); if (targ < 1) { if (errors != NULL) { item_list_append_format( - errors, - _("invalid value provided for \"%s\""), - name); + errors, + _("invalid value provided for \"%s\""), + name); } return; } @@ -852,9 +863,9 @@ parse_time_unit_parameter(const char *name, const char *value, char *dest, ItemL if (errors != NULL) { item_list_append_format( - errors, - _("value provided for \"%s\" must be one of ms/s/min/h/d"), - name); + errors, + _("value provided for \"%s\" must be one of ms/s/min/h/d"), + name); return; } } @@ -909,11 +920,11 @@ reload_config(t_configuration_options *orig_options) { PGconn *conn; t_configuration_options new_options = T_CONFIGURATION_OPTIONS_INITIALIZER; - bool config_changed = false; - bool log_config_changed = false; + bool config_changed = false; + bool log_config_changed = false; - static ItemList config_errors = { NULL, NULL }; - static ItemList config_warnings = { NULL, NULL }; + static ItemList config_errors = {NULL, NULL}; + static ItemList config_warnings = {NULL, NULL}; log_info(_("reloading configuration file")); @@ -980,7 +991,7 @@ reload_config(t_configuration_options *orig_options) /* conninfo */ if (strcmp(orig_options->conninfo, new_options.conninfo) != 0) { - /* Test conninfo string works*/ + /* Test conninfo string works */ conn = establish_db_connection(new_options.conninfo, false); if (!conn || (PQstatus(conn) != CONNECTION_OK)) { @@ -1228,13 +1239,14 @@ print_item_list(ItemList *item_list) int repmgr_atoi(const char *value, const char *config_item, ItemList *error_list, int minval) { - char *endptr = NULL; - long longval = 0; + char *endptr = NULL; + long longval = 0; PQExpBufferData errors; initPQExpBuffer(&errors); - /* It's possible that some versions of strtol() don't treat an empty + /* + * It's possible that some versions of strtol() don't treat an empty * string as an error. */ if (*value == '\0') @@ -1253,14 +1265,14 @@ repmgr_atoi(const char *value, const char *config_item, ItemList *error_list, in _("\"%s\": invalid value (provided: \"%s\")"), config_item, value); } - else if ((int32)longval < longval) + else if ((int32) longval < longval) { appendPQExpBuffer(&errors, _("\"%s\": must be a positive signed 32 bit integer, i.e. 2147483647 or less (provided: \"%s\")"), config_item, value); } - else if ((int32)longval < minval) + else if ((int32) longval < minval) /* Disallow negative values for most parameters */ { appendPQExpBuffer(&errors, @@ -1399,7 +1411,7 @@ tablespace_list_append(t_configuration_options *options, const char *arg) if (!*cell->old_dir || !*cell->new_dir) { log_error(_("invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\""), - arg); + arg); exit(ERR_BAD_CONFIG); } @@ -1505,20 +1517,21 @@ clear_event_notification_list(t_configuration_options *options) bool parse_pg_basebackup_options(const char *pg_basebackup_options, t_basebackup_options *backup_options, int server_version_num, ItemList *error_list) { - int options_len = 0; - char *options_string = NULL; - char *options_string_ptr = NULL; + int options_len = 0; + char *options_string = NULL; + char *options_string_ptr = NULL; /* - * Add parsed options to this list, then copy to an array - * to pass to getopt + * Add parsed options to this list, then copy to an array to pass to + * getopt */ - static ItemList option_argv = { NULL, NULL }; + static ItemList option_argv = {NULL, NULL}; - char *argv_item = NULL; - int c, argc_item = 1; + char *argv_item = NULL; + int c, + argc_item = 1; - char **argv_array = NULL; + char **argv_array = NULL; ItemListCell *cell = NULL; int optindex = 0; @@ -1536,8 +1549,8 @@ parse_pg_basebackup_options(const char *pg_basebackup_options, t_basebackup_opti }; /* - * From PostgreSQL 10, --xlog-method is renamed --wal-method - * and there's also --no-slot, which we'll want to consider. + * From PostgreSQL 10, --xlog-method is renamed --wal-method and there's + * also --no-slot, which we'll want to consider. */ static struct option long_options_10[] = { @@ -1576,8 +1589,8 @@ parse_pg_basebackup_options(const char *pg_basebackup_options, t_basebackup_opti /* * Array of argument values to pass to getopt_long - this will need to - * include an empty string as the first value (normally this would be - * the program name) + * include an empty string as the first value (normally this would be the + * program name) */ argv_array = pg_malloc0(sizeof(char *) * (argc_item + 2)); @@ -1591,7 +1604,7 @@ parse_pg_basebackup_options(const char *pg_basebackup_options, t_basebackup_opti */ for (cell = option_argv.head; cell; cell = cell->next) { - int argv_len = strlen(cell->string) + 1; + int argv_len = strlen(cell->string) + 1; argv_array[c] = pg_malloc0(argv_len); @@ -1647,8 +1660,9 @@ parse_pg_basebackup_options(const char *pg_basebackup_options, t_basebackup_opti pfree(options_string); { - int i; - for (i = 0; i < argc_item + 2; i ++) + int i; + + for (i = 0; i < argc_item + 2; i++) pfree(argv_array[i]); } pfree(argv_array); diff --git a/configfile.h b/configfile.h index c79180de..0643dba9 100644 --- a/configfile.h +++ b/configfile.h @@ -28,18 +28,19 @@ /* magic number for use in t_recovery_conf */ #define TARGET_TIMELINE_LATEST 0 -extern bool config_file_found; -extern char config_file_path[MAXPGPATH]; +extern bool config_file_found; +extern char config_file_path[MAXPGPATH]; -typedef enum { +typedef enum +{ FAILOVER_MANUAL, FAILOVER_AUTOMATIC -} failover_mode_opt; +} failover_mode_opt; typedef struct EventNotificationListCell { struct EventNotificationListCell *next; - char event_type[MAXLEN]; + char event_type[MAXLEN]; } EventNotificationListCell; typedef struct EventNotificationList @@ -67,7 +68,7 @@ typedef struct TablespaceList typedef struct { /* node information */ - int node_id; + int node_id; char node_name[MAXLEN]; char conninfo[MAXLEN]; char replication_user[NAMEDATALEN]; @@ -98,7 +99,7 @@ typedef struct int replication_lag_critical; /* repmgrd settings */ - failover_mode_opt failover; + failover_mode_opt failover; char location[MAXLEN]; int priority; char promote_command[MAXLEN]; @@ -136,7 +137,7 @@ typedef struct /* undocumented test settings */ int promote_delay; -} t_configuration_options; +} t_configuration_options; /* * The following will initialize the structure with a minimal set of options; @@ -180,13 +181,14 @@ typedef struct { char slot[MAXLEN]; char xlog_method[MAXLEN]; - bool no_slot; /* from PostgreSQL 10 */ + bool no_slot; /* from PostgreSQL 10 */ } t_basebackup_options; #define T_BASEBACKUP_OPTIONS_INITIALIZER { "", "", false } -typedef enum { +typedef enum +{ RTA_PAUSE, RTA_PROMOTE, RTA_SHUTDOWN @@ -204,22 +206,22 @@ typedef enum { typedef struct { /* archive recovery settings */ - char restore_command[MAXLEN]; - char archive_cleanup_command[MAXLEN]; - char recovery_end_command[MAXLEN]; + char restore_command[MAXLEN]; + char archive_cleanup_command[MAXLEN]; + char recovery_end_command[MAXLEN]; /* recovery target settings */ - char recovery_target_name[MAXLEN]; - char recovery_target_time[MAXLEN]; - char recovery_target_xid[MAXLEN]; - bool recovery_target_inclusive; - int recovery_target_timeline; - RecoveryTargetAction recovery_target_action; /* default: RTA_PAUSE */ + char recovery_target_name[MAXLEN]; + char recovery_target_time[MAXLEN]; + char recovery_target_xid[MAXLEN]; + bool recovery_target_inclusive; + int recovery_target_timeline; + RecoveryTargetAction recovery_target_action; /* default: RTA_PAUSE */ /* standby server settings */ - bool standby_mode; - char primary_conninfo[MAXLEN]; - char primary_slot_name[MAXLEN]; - char trigger_file[MAXLEN]; - char recovery_min_apply_delay[MAXLEN]; + bool standby_mode; + char primary_conninfo[MAXLEN]; + char primary_slot_name[MAXLEN]; + char trigger_file[MAXLEN]; + char recovery_min_apply_delay[MAXLEN]; } t_recovery_conf; #define T_RECOVERY_CONF_INITIALIZER { \ @@ -245,19 +247,19 @@ bool reload_config(t_configuration_options *orig_options); bool parse_recovery_conf(const char *data_dir, t_recovery_conf *conf); -int repmgr_atoi(const char *s, - const char *config_item, - ItemList *error_list, - int minval); +int repmgr_atoi(const char *s, + const char *config_item, + ItemList *error_list, + int minval); bool parse_pg_basebackup_options(const char *pg_basebackup_options, - t_basebackup_options *backup_options, - int server_version_num, - ItemList *error_list); + t_basebackup_options *backup_options, + int server_version_num, + ItemList *error_list); /* called by repmgr-client and repmgrd */ -void exit_with_cli_errors(ItemList *error_list); -void print_item_list(ItemList *item_list); +void exit_with_cli_errors(ItemList *error_list); +void print_item_list(ItemList *item_list); -#endif /* _REPMGR_CONFIGFILE_H_ */ +#endif /* _REPMGR_CONFIGFILE_H_ */ diff --git a/controldata.c b/controldata.c index 4992b4d9..3061d42b 100644 --- a/controldata.c +++ b/controldata.c @@ -34,7 +34,7 @@ uint64 get_system_identifier(const char *data_directory) { ControlFileInfo *control_file_info = NULL; - uint64 system_identifier = UNKNOWN_SYSTEM_IDENTIFIER; + uint64 system_identifier = UNKNOWN_SYSTEM_IDENTIFIER; control_file_info = get_controlfile(data_directory); @@ -53,7 +53,7 @@ DBState get_db_state(const char *data_directory) { ControlFileInfo *control_file_info = NULL; - DBState state; + DBState state; control_file_info = get_controlfile(data_directory); @@ -74,7 +74,7 @@ extern XLogRecPtr get_latest_checkpoint_location(const char *data_directory) { ControlFileInfo *control_file_info = NULL; - XLogRecPtr checkPoint = InvalidXLogRecPtr; + XLogRecPtr checkPoint = InvalidXLogRecPtr; control_file_info = get_controlfile(data_directory); @@ -94,7 +94,7 @@ int get_data_checksum_version(const char *data_directory) { ControlFileInfo *control_file_info = NULL; - int data_checksum_version = -1; + int data_checksum_version = -1; control_file_info = get_controlfile(data_directory); @@ -104,7 +104,7 @@ get_data_checksum_version(const char *data_directory) } else { - data_checksum_version = (int)control_file_info->control_file->data_checksum_version; + data_checksum_version = (int) control_file_info->control_file->data_checksum_version; } pfree(control_file_info->control_file); diff --git a/controldata.h b/controldata.h index e3ca9e21..70c9d9db 100644 --- a/controldata.h +++ b/controldata.h @@ -14,14 +14,14 @@ typedef struct { - bool control_file_processed; + bool control_file_processed; ControlFileData *control_file; } ControlFileInfo; extern DBState get_db_state(const char *data_directory); -extern const char * describe_db_state(DBState state); -extern int get_data_checksum_version(const char *data_directory); +extern const char *describe_db_state(DBState state); +extern int get_data_checksum_version(const char *data_directory); extern uint64 get_system_identifier(const char *data_directory); extern XLogRecPtr get_latest_checkpoint_location(const char *data_directory); -#endif /* _CONTROLDATA_H_ */ +#endif /* _CONTROLDATA_H_ */ diff --git a/dbutils.c b/dbutils.c index ea0b4403..fabe3da0 100644 --- a/dbutils.c +++ b/dbutils.c @@ -35,11 +35,11 @@ int server_version_num = UNKNOWN_SERVER_VERSION_NUM; static PGconn *_establish_db_connection(const char *conninfo, - const bool exit_on_error, - const bool log_notice, - const bool verbose_only); + const bool exit_on_error, + const bool log_notice, + const bool verbose_only); -static PGconn *_get_primary_connection(PGconn *standby_conn, int *primary_id, char *primary_conninfo_out, bool quiet); +static PGconn *_get_primary_connection(PGconn *standby_conn, int *primary_id, char *primary_conninfo_out, bool quiet); static bool _set_config(PGconn *conn, const char *config_param, const char *sqlquery); static RecordStatus _get_node_record(PGconn *conn, char *sqlquery, t_node_info *node_info); @@ -48,7 +48,7 @@ static void _populate_node_record(PGresult *res, t_node_info *node_info, int row static void _populate_node_records(PGresult *res, NodeInfoList *node_list); static bool _create_update_node_record(PGconn *conn, char *action, t_node_info *node_info); -static bool _create_event(PGconn *conn, t_configuration_options *options, int node_id, char *event, bool successful, char *details, t_event_info *event_info, bool send_notification); +static bool _create_event(PGconn *conn, t_configuration_options *options, int node_id, char *event, bool successful, char *details, t_event_info *event_info, bool send_notification); static void _populate_bdr_node_record(PGresult *res, t_bdr_node_info *node_info, int row); static void _populate_bdr_node_records(PGresult *res, BdrNodeInfoList *node_list); @@ -61,11 +61,12 @@ static void _populate_bdr_node_records(PGresult *res, BdrNodeInfoList *node_list XLogRecPtr parse_lsn(const char *str) { - XLogRecPtr ptr = InvalidXLogRecPtr; - uint32 high, low; + XLogRecPtr ptr = InvalidXLogRecPtr; + uint32 high, + low; if (sscanf(str, "%x/%x", &high, &low) == 2) - ptr = (((XLogRecPtr)high) << 32) + (XLogRecPtr)low; + ptr = (((XLogRecPtr) high) << 32) + (XLogRecPtr) low; return ptr; } @@ -75,7 +76,7 @@ parse_lsn(const char *str) * Wrap query with appropriate DDL function, if required. */ void -wrap_ddl_query(PQExpBufferData *query_buf, int replication_type, const char *fmt, ...) +wrap_ddl_query(PQExpBufferData *query_buf, int replication_type, const char *fmt,...) { va_list arglist; char buf[MAXLEN]; @@ -145,7 +146,7 @@ _establish_db_connection(const char *conninfo, const bool exit_on_error, const b /* Check to see that the backend connection was successfully made */ if ((PQstatus(conn) != CONNECTION_OK)) { - bool emit_log = true; + bool emit_log = true; if (verbose_only == true && verbose_logging == false) emit_log = false; @@ -175,7 +176,8 @@ _establish_db_connection(const char *conninfo, const bool exit_on_error, const b } /* - * set "synchronous_commit" to "local" in case synchronous replication is in use + * set "synchronous_commit" to "local" in case synchronous replication is + * in use * * XXX set this explicitly before any write operations */ @@ -218,11 +220,12 @@ establish_db_connection_quiet(const char *conninfo) PGconn -*establish_primary_db_connection(PGconn *conn, + * +establish_primary_db_connection(PGconn *conn, const bool exit_on_error) { - t_node_info primary_node_info = T_NODE_INFO_INITIALIZER; - bool primary_record_found = get_primary_node_record(conn, &primary_node_info); + t_node_info primary_node_info = T_NODE_INFO_INITIALIZER; + bool primary_record_found = get_primary_node_record(conn, &primary_node_info); if (primary_record_found == false) { @@ -275,7 +278,7 @@ establish_db_connection_by_params(t_conninfo_param_list *param_list, param_set_ine(param_list, "fallback_application_name", "repmgr"); /* Connect to the database using the provided parameters */ - conn = PQconnectdbParams((const char**)param_list->keywords, (const char**)param_list->values, true); + conn = PQconnectdbParams((const char **) param_list->keywords, (const char **) param_list->values, true); /* Check to see that the backend connection was successfully made */ if ((PQstatus(conn) != CONNECTION_OK)) @@ -294,8 +297,8 @@ establish_db_connection_by_params(t_conninfo_param_list *param_list, int i; /* - * set "synchronous_commit" to "local" in case synchronous replication is in - * use (provided this is not a replication connection) + * set "synchronous_commit" to "local" in case synchronous replication + * is in use (provided this is not a replication connection) */ for (i = 0; param_list->keywords[i]; i++) @@ -321,9 +324,9 @@ establish_db_connection_by_params(t_conninfo_param_list *param_list, bool is_superuser_connection(PGconn *conn, t_connection_user *userinfo) { - char *current_user = NULL; - const char *superuser_status = NULL; - bool is_superuser = false; + char *current_user = NULL; + const char *superuser_status = NULL; + bool is_superuser = false; current_user = PQuser(conn); superuser_status = PQparameterStatus(conn, "is_superuser"); @@ -391,14 +394,14 @@ initialize_conninfo_params(t_conninfo_param_list *param_list, bool set_defaults) { PQconninfoOption *defs = NULL; PQconninfoOption *def = NULL; - int c; + int c; defs = PQconndefaults(); param_list->size = 0; /* Count maximum number of parameters */ for (def = defs; def->keyword; def++) - param_list->size ++; + param_list->size++; /* Initialize our internal parameter list */ param_list->keywords = pg_malloc0(sizeof(char *) * (param_list->size + 1)); @@ -430,7 +433,7 @@ initialize_conninfo_params(t_conninfo_param_list *param_list, bool set_defaults) void free_conninfo_params(t_conninfo_param_list *param_list) { - int c; + int c; for (c = 0; c < param_list->size; c++) { @@ -450,7 +453,8 @@ free_conninfo_params(t_conninfo_param_list *param_list) void copy_conninfo_params(t_conninfo_param_list *dest_list, t_conninfo_param_list *source_list) { - int c; + int c; + for (c = 0; c < source_list->size && source_list->keywords[c] != NULL; c++) { if (source_list->values[c] != NULL && source_list->values[c][0] != '\0') @@ -463,8 +467,8 @@ copy_conninfo_params(t_conninfo_param_list *dest_list, t_conninfo_param_list *so void param_set(t_conninfo_param_list *param_list, const char *param, const char *value) { - int c; - int value_len = strlen(value) + 1; + int c; + int value_len = strlen(value) + 1; /* * Scan array to see if the parameter is already set - if not, replace it @@ -488,7 +492,8 @@ param_set(t_conninfo_param_list *param_list, const char *param, const char *valu */ if (c < param_list->size) { - int param_len = strlen(param) + 1; + int param_len = strlen(param) + 1; + param_list->keywords[c] = pg_malloc0(param_len); param_list->values[c] = pg_malloc0(value_len); @@ -497,9 +502,9 @@ param_set(t_conninfo_param_list *param_list, const char *param, const char *valu } /* - * It's theoretically possible a parameter couldn't be added as - * the array is full, but it's highly improbable so we won't - * handle it at the moment. + * It's theoretically possible a parameter couldn't be added as the array + * is full, but it's highly improbable so we won't handle it at the + * moment. */ } @@ -510,8 +515,8 @@ param_set(t_conninfo_param_list *param_list, const char *param, const char *valu void param_set_ine(t_conninfo_param_list *param_list, const char *param, const char *value) { - int c; - int value_len = strlen(value) + 1; + int c; + int value_len = strlen(value) + 1; /* * Scan array to see if the parameter is already set - if so, do nothing @@ -530,7 +535,8 @@ param_set_ine(t_conninfo_param_list *param_list, const char *param, const char * */ if (c < param_list->size) { - int param_len = strlen(param) + 1; + int param_len = strlen(param) + 1; + param_list->keywords[c] = pg_malloc0(param_len); param_list->values[c] = pg_malloc0(value_len); @@ -543,7 +549,7 @@ param_set_ine(t_conninfo_param_list *param_list, const char *param, const char * char * param_get(t_conninfo_param_list *param_list, const char *param) { - int c; + int c; for (c = 0; c < param_list->size && param_list->keywords[c] != NULL; c++) { @@ -585,7 +591,7 @@ parse_conninfo_string(const char *conninfo_str, t_conninfo_param_list *param_lis { /* Ignore non-set or blank parameter values */ if ((option->val == NULL) || - (option->val != NULL && option->val[0] == '\0')) + (option->val != NULL && option->val[0] == '\0')) continue; /* Ignore application_name */ @@ -623,7 +629,7 @@ conn_to_param_list(PGconn *conn, t_conninfo_param_list *param_list) { /* Ignore non-set or blank parameter values */ if ((option->val == NULL) || - (option->val != NULL && option->val[0] == '\0')) + (option->val != NULL && option->val[0] == '\0')) continue; param_set(param_list, option->keyword, option->val); @@ -639,10 +645,10 @@ conn_to_param_list(PGconn *conn, t_conninfo_param_list *param_list) char * param_list_to_string(t_conninfo_param_list *param_list) { - int c; + int c; PQExpBufferData conninfo_buf; - char *conninfo_str = NULL; - int len = 0; + char *conninfo_str = NULL; + int len = 0; initPQExpBuffer(&conninfo_buf); @@ -773,10 +779,10 @@ _set_config(PGconn *conn, const char *config_param, const char *sqlquery) bool -set_config(PGconn *conn, const char *config_param, const char *config_value) +set_config(PGconn *conn, const char *config_param, const char *config_value) { - PQExpBufferData query; - bool result = false; + PQExpBufferData query; + bool result = false; initPQExpBuffer(&query); appendPQExpBuffer(&query, @@ -796,8 +802,8 @@ set_config(PGconn *conn, const char *config_param, const char *config_value) bool set_config_bool(PGconn *conn, const char *config_param, bool state) { - PQExpBufferData query; - bool result = false; + PQExpBufferData query; + bool result = false; initPQExpBuffer(&query); appendPQExpBuffer(&query, @@ -820,12 +826,12 @@ int guc_set(PGconn *conn, const char *parameter, const char *op, const char *value) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; int retval = 1; - char *escaped_parameter = escape_string(conn, parameter); - char *escaped_value = escape_string(conn, value); + char *escaped_parameter = escape_string(conn, parameter); + char *escaped_value = escape_string(conn, value); initPQExpBuffer(&query); appendPQExpBuffer(&query, @@ -865,12 +871,12 @@ int guc_set_typed(PGconn *conn, const char *parameter, const char *op, const char *value, const char *datatype) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; int retval = 1; - char *escaped_parameter = escape_string(conn, parameter); - char *escaped_value = escape_string(conn, value); + char *escaped_parameter = escape_string(conn, parameter); + char *escaped_value = escape_string(conn, value); initPQExpBuffer(&query); appendPQExpBuffer(&query, @@ -889,7 +895,7 @@ guc_set_typed(PGconn *conn, const char *parameter, const char *op, if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_error(_("guc_set_typed(): unable to execute query\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); retval = -1; } else if (PQntuples(res) == 0) @@ -906,12 +912,12 @@ guc_set_typed(PGconn *conn, const char *parameter, const char *op, bool get_pg_setting(PGconn *conn, const char *setting, char *output) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; int i; - bool success = false; + bool success = false; - char *escaped_setting = escape_string(conn, setting); + char *escaped_setting = escape_string(conn, setting); if (escaped_setting == NULL) { @@ -935,7 +941,7 @@ get_pg_setting(PGconn *conn, const char *setting, char *output) if (res == NULL || PQresultStatus(res) != PGRES_TUPLES_OK) { log_error(_("get_pg_setting() - PQexec failed: %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); PQclear(res); return false; } @@ -974,7 +980,7 @@ get_pg_setting(PGconn *conn, const char *setting, char *output) bool get_cluster_size(PGconn *conn, char *size) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); @@ -1009,7 +1015,7 @@ int get_server_version(PGconn *conn, char *server_version) { PGresult *res = NULL; - int server_version_num; + int server_version_num; res = PQexec(conn, "SELECT pg_catalog.current_setting('server_version_num'), " @@ -1028,7 +1034,7 @@ get_server_version(PGconn *conn, char *server_version) server_version_num = atoi(PQgetvalue(res, 0, 0)); - PQclear(res); + PQclear(res); return server_version_num; } @@ -1048,7 +1054,7 @@ get_recovery_type(PGconn *conn) if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_error(_("unable to determine if server is in recovery:\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); recovery_type = RECTYPE_UNKNOWN; } else if (PQntuples(res) == 1) @@ -1083,7 +1089,7 @@ PGconn * _get_primary_connection(PGconn *conn, int *primary_id, char *primary_conninfo_out, bool quiet) { - PQExpBufferData query; + PQExpBufferData query; PGconn *remote_conn = NULL; PGresult *res = NULL; @@ -1190,7 +1196,7 @@ _get_primary_connection(PGconn *conn, PGconn * get_primary_connection(PGconn *conn, - int *primary_id, char *primary_conninfo_out) + int *primary_id, char *primary_conninfo_out) { return _get_primary_connection(conn, primary_id, primary_conninfo_out, false); } @@ -1198,7 +1204,7 @@ get_primary_connection(PGconn *conn, PGconn * get_primary_connection_quiet(PGconn *conn, - int *primary_id, char *primary_conninfo_out) + int *primary_id, char *primary_conninfo_out) { return _get_primary_connection(conn, primary_id, primary_conninfo_out, true); } @@ -1214,7 +1220,7 @@ get_primary_connection_quiet(PGconn *conn, int get_primary_node_id(PGconn *conn) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; int retval = NODE_NOT_FOUND; @@ -1254,49 +1260,45 @@ get_primary_node_id(PGconn *conn) bool get_replication_info(PGconn *conn, ReplInfo *replication_info) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; if (server_version_num == UNKNOWN_SERVER_VERSION_NUM) server_version_num = get_server_version(conn, NULL); initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT ts, " - " last_wal_receive_lsn, " - " last_wal_replay_lsn, " - " last_xact_replay_timestamp, " - " CASE WHEN (last_wal_receive_lsn = last_wal_replay_lsn) " - " THEN 0::INT " - " ELSE " - " EXTRACT(epoch FROM (pg_catalog.clock_timestamp() - last_xact_replay_timestamp))::INT " - " END AS replication_lag_time, " - " COALESCE(last_wal_receive_lsn, '0/0') >= last_wal_replay_lsn AS receiving_streamed_wal " - " FROM ( "); + appendPQExpBuffer(&query, + " SELECT ts, " + " last_wal_receive_lsn, " + " last_wal_replay_lsn, " + " last_xact_replay_timestamp, " + " CASE WHEN (last_wal_receive_lsn = last_wal_replay_lsn) " + " THEN 0::INT " + " ELSE " + " EXTRACT(epoch FROM (pg_catalog.clock_timestamp() - last_xact_replay_timestamp))::INT " + " END AS replication_lag_time, " + " COALESCE(last_wal_receive_lsn, '0/0') >= last_wal_replay_lsn AS receiving_streamed_wal " + " FROM ( "); if (server_version_num >= 100000) { - appendPQExpBuffer( - &query, - " SELECT CURRENT_TIMESTAMP AS ts, " - " pg_catalog.pg_last_wal_receive_lsn() AS last_wal_receive_lsn, " - " pg_catalog.pg_last_wal_replay_lsn() AS last_wal_replay_lsn, " - " pg_catalog.pg_last_xact_replay_timestamp() AS last_xact_replay_timestamp "); + appendPQExpBuffer(&query, + " SELECT CURRENT_TIMESTAMP AS ts, " + " pg_catalog.pg_last_wal_receive_lsn() AS last_wal_receive_lsn, " + " pg_catalog.pg_last_wal_replay_lsn() AS last_wal_replay_lsn, " + " pg_catalog.pg_last_xact_replay_timestamp() AS last_xact_replay_timestamp "); } else { - appendPQExpBuffer( - &query, - " SELECT CURRENT_TIMESTAMP AS ts, " - " pg_catalog.pg_last_xlog_receive_location() AS last_wal_receive_lsn, " - " pg_catalog.pg_last_xlog_replay_location() AS last_wal_replay_lsn, " - " pg_catalog.pg_last_xact_replay_timestamp() AS last_xact_replay_timestamp "); + appendPQExpBuffer(&query, + " SELECT CURRENT_TIMESTAMP AS ts, " + " pg_catalog.pg_last_xlog_receive_location() AS last_wal_receive_lsn, " + " pg_catalog.pg_last_xlog_replay_location() AS last_wal_replay_lsn, " + " pg_catalog.pg_last_xact_replay_timestamp() AS last_xact_replay_timestamp "); } - appendPQExpBuffer( - &query, - " ) q "); + appendPQExpBuffer(&query, + " ) q "); log_verbose(LOG_DEBUG, "get_replication_info():\n%s", query.data); @@ -1306,7 +1308,7 @@ get_replication_info(PGconn *conn, ReplInfo *replication_info) if (PQresultStatus(res) != PGRES_TUPLES_OK || !PQntuples(res)) { log_error(_("unable to execute replication info query:\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); PQclear(res); return false; @@ -1318,6 +1320,7 @@ get_replication_info(PGconn *conn, ReplInfo *replication_info) strncpy(replication_info->last_xact_replay_timestamp, PQgetvalue(res, 0, 3), MAXLEN); replication_info->replication_lag_time = atoi(PQgetvalue(res, 0, 4)); replication_info->receiving_streamed_wal = atobool(PQgetvalue(res, 0, 5)); + PQclear(res); return true; @@ -1327,16 +1330,15 @@ get_replication_info(PGconn *conn, ReplInfo *replication_info) bool can_use_pg_rewind(PGconn *conn, const char *data_directory, PQExpBufferData *reason) { - bool can_use = true; + bool can_use = true; if (server_version_num == UNKNOWN_SERVER_VERSION_NUM) server_version_num = get_server_version(conn, NULL); if (server_version_num < 90500) { - appendPQExpBuffer( - reason, - _("pg_rewind available from PostgreSQL 9.5")); + appendPQExpBuffer(reason, + _("pg_rewind available from PostgreSQL 9.5")); return false; } @@ -1345,31 +1347,29 @@ can_use_pg_rewind(PGconn *conn, const char *data_directory, PQExpBufferData *rea if (can_use == false) appendPQExpBuffer(reason, "; "); - appendPQExpBuffer( - reason, - _("\"full_page_writes\" must be set to \"on\"")); + appendPQExpBuffer(reason, + _("\"full_page_writes\" must be set to \"on\"")); can_use = false; } /* - * "wal_log_hints" off - are data checksums available? - * Note: we're checking the local pg_control file here as the value will - * be the same throughout the cluster and saves a round-trip to the - * demotion candidate. + * "wal_log_hints" off - are data checksums available? Note: we're + * checking the local pg_control file here as the value will be the same + * throughout the cluster and saves a round-trip to the demotion + * candidate. */ if (guc_set(conn, "wal_log_hints", "=", "on") == false) { - int data_checksum_version = get_data_checksum_version(data_directory); + int data_checksum_version = get_data_checksum_version(data_directory); if (data_checksum_version < 0) { if (can_use == false) appendPQExpBuffer(reason, "; "); - appendPQExpBuffer( - reason, - _("\"wal_log_hints\" is set to \"off\" but unable to determine checksum version")); + appendPQExpBuffer(reason, + _("\"wal_log_hints\" is set to \"off\" but unable to determine checksum version")); can_use = false; } else if (data_checksum_version == 0) @@ -1377,9 +1377,8 @@ can_use_pg_rewind(PGconn *conn, const char *data_directory, PQExpBufferData *rea if (can_use == false) appendPQExpBuffer(reason, "; "); - appendPQExpBuffer( - reason, - _("\"wal_log_hints\" is set to \"off\" and checksums are disabled")); + appendPQExpBuffer(reason, + _("\"wal_log_hints\" is set to \"off\" and checksums are disabled")); can_use = false; } @@ -1392,12 +1391,12 @@ can_use_pg_rewind(PGconn *conn, const char *data_directory, PQExpBufferData *rea int get_ready_archive_files(PGconn *conn, const char *data_directory) { - char archive_status_dir[MAXPGPATH] = ""; + char archive_status_dir[MAXPGPATH] = ""; struct stat statbuf; struct dirent *arcdir_ent; - DIR *arcdir; + DIR *arcdir; - int ready_count = 0; + int ready_count = 0; if (server_version_num == UNKNOWN_SERVER_VERSION_NUM) server_version_num = get_server_version(conn, NULL); @@ -1421,7 +1420,7 @@ get_ready_archive_files(PGconn *conn, const char *data_directory) log_error(_("unable to access archive_status directory \"%s\""), archive_status_dir); log_detail("%s", strerror(errno)); - /* XXX magic number*/ + /* XXX magic number */ return -1; } @@ -1432,15 +1431,15 @@ get_ready_archive_files(PGconn *conn, const char *data_directory) log_error(_("unable to open archive directory \"%s\""), archive_status_dir); log_detail("%s", strerror(errno)); - /* XXX magic number*/ + /* XXX magic number */ return -1; } while ((arcdir_ent = readdir(arcdir)) != NULL) { struct stat statbuf; - char file_path[MAXPGPATH] = ""; - int basenamelen = 0; + char file_path[MAXPGPATH] = ""; + int basenamelen = 0; snprintf(file_path, MAXPGPATH, "%s/%s", @@ -1453,14 +1452,14 @@ get_ready_archive_files(PGconn *conn, const char *data_directory) continue; } - basenamelen = (int) strlen(arcdir_ent->d_name) - 6; + basenamelen = (int) strlen(arcdir_ent->d_name) - 6; /* - * count anything ending in ".ready"; for a more precise implementation - * see: src/backend/postmaster/pgarch.c + * count anything ending in ".ready"; for a more precise + * implementation see: src/backend/postmaster/pgarch.c */ if (strcmp(arcdir_ent->d_name + basenamelen, ".ready") == 0) - ready_count ++; + ready_count++; } closedir(arcdir); @@ -1472,9 +1471,9 @@ get_ready_archive_files(PGconn *conn, const char *data_directory) int get_replication_lag_seconds(PGconn *conn) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; - int lag_seconds = 0; + int lag_seconds = 0; if (server_version_num == UNKNOWN_SERVER_VERSION_NUM) server_version_num = get_server_version(conn, NULL); @@ -1483,24 +1482,21 @@ get_replication_lag_seconds(PGconn *conn) if (server_version_num >= 100000) { - appendPQExpBuffer( - &query, - " SELECT CASE WHEN (pg_catalog.pg_last_wal_receive_lsn() = pg_catalog.pg_last_wal_replay_lsn()) "); + appendPQExpBuffer(&query, + " SELECT CASE WHEN (pg_catalog.pg_last_wal_receive_lsn() = pg_catalog.pg_last_wal_replay_lsn()) "); } else { - appendPQExpBuffer( - &query, - " SELECT CASE WHEN (pg_catalog.pg_last_xlog_receive_location() = pg_catalog.pg_last_xlog_replay_location()) "); + appendPQExpBuffer(&query, + " SELECT CASE WHEN (pg_catalog.pg_last_xlog_receive_location() = pg_catalog.pg_last_xlog_replay_location()) "); } - appendPQExpBuffer( - &query, - " THEN 0 " - " ELSE EXTRACT(epoch FROM (pg_catalog.clock_timestamp() - pg_catalog.pg_last_xact_replay_timestamp()))::INT " - " END " - " AS lag_seconds"); + appendPQExpBuffer(&query, + " THEN 0 " + " ELSE EXTRACT(epoch FROM (pg_catalog.clock_timestamp() - pg_catalog.pg_last_xact_replay_timestamp()))::INT " + " END " + " AS lag_seconds"); res = PQexec(conn, query.data); log_verbose(LOG_DEBUG, "get_replication_lag_seconds():\n%s", query.data); @@ -1520,7 +1516,7 @@ get_replication_lag_seconds(PGconn *conn) return -1; } - lag_seconds = atoi(PQgetvalue(res, 0, 0)); + lag_seconds = atoi(PQgetvalue(res, 0, 0)); PQclear(res); return lag_seconds; @@ -1530,7 +1526,7 @@ get_replication_lag_seconds(PGconn *conn) bool identify_system(PGconn *repl_conn, t_system_identification *identification) { - PGresult *res = NULL; + PGresult *res = NULL; res = PQexec(repl_conn, "IDENTIFY_SYSTEM;"); @@ -1541,7 +1537,7 @@ identify_system(PGconn *repl_conn, t_system_identification *identification) } identification->system_identifier = atol(PQgetvalue(res, 0, 0)); - identification->timeline = atoi(PQgetvalue(res, 0, 1)); + identification->timeline = atoi(PQgetvalue(res, 0, 1)); identification->xlogpos = parse_lsn(PQgetvalue(res, 0, 2)); PQclear(res); @@ -1552,15 +1548,14 @@ identify_system(PGconn *repl_conn, t_system_identification *identification) bool repmgrd_set_local_node_id(PGconn *conn, int local_node_id) { - PQExpBufferData query; - PGresult *res = NULL; + PQExpBufferData query; + PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT repmgr.set_local_node_id(%i)", - local_node_id); + appendPQExpBuffer(&query, + " SELECT repmgr.set_local_node_id(%i)", + local_node_id); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -1581,7 +1576,8 @@ repmgrd_set_local_node_id(PGconn *conn, int local_node_id) /* result functions */ /* ================ */ -bool atobool(const char *value) +bool +atobool(const char *value) { return (strcmp(value, "t") == 0) ? true @@ -1596,9 +1592,9 @@ bool atobool(const char *value) ExtensionStatus get_repmgr_extension_status(PGconn *conn) { - PQExpBufferData query; - PGresult *res = NULL; - ExtensionStatus status = REPMGR_UNKNOWN; + PQExpBufferData query; + PGresult *res = NULL; + ExtensionStatus status = REPMGR_UNKNOWN; /* TODO: check version */ @@ -1618,7 +1614,7 @@ get_repmgr_extension_status(PGconn *conn) if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_error(_("unable to execute extension query:\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); status = REPMGR_UNKNOWN; } @@ -1674,7 +1670,7 @@ checkpoint(PGconn *conn) static RecordStatus _get_node_record(PGconn *conn, char *sqlquery, t_node_info *node_info) { - int ntuples = 0; + int ntuples = 0; PGresult *res = NULL; res = PQexec(conn, sqlquery); @@ -1760,7 +1756,7 @@ parse_node_type(const char *type) const char * get_node_type_string(t_server_type type) { - switch(type) + switch (type) { case PRIMARY: return "primary"; @@ -1768,7 +1764,7 @@ get_node_type_string(t_server_type type) return "standby"; case BDR: return "bdr"; - /* this should never happen */ + /* this should never happen */ case UNKNOWN: default: log_error(_("unknown node type %i"), type); @@ -1780,8 +1776,8 @@ get_node_type_string(t_server_type type) RecordStatus get_node_record(PGconn *conn, int node_id, t_node_info *node_info) { - PQExpBufferData query; - RecordStatus result; + PQExpBufferData query; + RecordStatus result; initPQExpBuffer(&query); appendPQExpBuffer(&query, @@ -1807,16 +1803,16 @@ get_node_record(PGconn *conn, int node_id, t_node_info *node_info) RecordStatus get_node_record_by_name(PGconn *conn, const char *node_name, t_node_info *node_info) { - PQExpBufferData query; - RecordStatus record_status = RECORD_NOT_FOUND; + PQExpBufferData query; + RecordStatus record_status = RECORD_NOT_FOUND; initPQExpBuffer(&query); appendPQExpBuffer(&query, - "SELECT " REPMGR_NODES_COLUMNS - " FROM repmgr.nodes " - " WHERE node_name = '%s' ", - node_name); + "SELECT " REPMGR_NODES_COLUMNS + " FROM repmgr.nodes " + " WHERE node_name = '%s' ", + node_name); log_verbose(LOG_DEBUG, "get_node_record_by_name():\n %s", query.data); @@ -1857,7 +1853,7 @@ get_primary_node_record(PGconn *conn, t_node_info *node_info) { RecordStatus record_status = RECORD_NOT_FOUND; - int primary_node_id = get_primary_node_id(conn); + int primary_node_id = get_primary_node_id(conn); if (primary_node_id == UNKNOWN_NODE_ID) { @@ -1878,7 +1874,7 @@ get_primary_node_record(PGconn *conn, t_node_info *node_info) bool get_local_node_record(PGconn *conn, int node_id, t_node_info *node_info) { - RecordStatus record_status = get_node_record(conn, node_id, node_info); + RecordStatus record_status = get_node_record(conn, node_id, node_info); if (record_status != RECORD_FOUND) { @@ -1895,9 +1891,10 @@ get_local_node_record(PGconn *conn, int node_id, t_node_info *node_info) static -void _populate_node_records(PGresult *res, NodeInfoList *node_list) +void +_populate_node_records(PGresult *res, NodeInfoList *node_list) { - int i; + int i; clear_node_info_list(node_list); @@ -1909,6 +1906,7 @@ void _populate_node_records(PGresult *res, NodeInfoList *node_list) for (i = 0; i < PQntuples(res); i++) { NodeInfoListCell *cell; + cell = (NodeInfoListCell *) pg_malloc0(sizeof(NodeInfoListCell)); cell->node_info = pg_malloc0(sizeof(t_node_info)); @@ -1931,16 +1929,15 @@ void _populate_node_records(PGresult *res, NodeInfoList *node_list) void get_all_node_records(PGconn *conn, NodeInfoList *node_list) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT " REPMGR_NODES_COLUMNS - " FROM repmgr.nodes " - "ORDER BY node_id "); + appendPQExpBuffer(&query, + " SELECT " REPMGR_NODES_COLUMNS + " FROM repmgr.nodes " + "ORDER BY node_id "); log_verbose(LOG_DEBUG, "get_all_node_records():\n%s", query.data); @@ -1958,18 +1955,17 @@ get_all_node_records(PGconn *conn, NodeInfoList *node_list) void get_downstream_node_records(PGconn *conn, int node_id, NodeInfoList *node_list) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT " REPMGR_NODES_COLUMNS - " FROM repmgr.nodes " - " WHERE upstream_node_id = %i " - "ORDER BY node_id ", - node_id); + appendPQExpBuffer(&query, + " SELECT " REPMGR_NODES_COLUMNS + " FROM repmgr.nodes " + " WHERE upstream_node_id = %i " + "ORDER BY node_id ", + node_id); log_verbose(LOG_DEBUG, "get_downstream_node_records():\n%s", query.data); @@ -1988,21 +1984,20 @@ get_downstream_node_records(PGconn *conn, int node_id, NodeInfoList *node_list) void get_active_sibling_node_records(PGconn *conn, int node_id, int upstream_node_id, NodeInfoList *node_list) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT " REPMGR_NODES_COLUMNS - " FROM repmgr.nodes " - " WHERE upstream_node_id = %i " - " AND node_id != %i " - " AND active IS TRUE " - "ORDER BY node_id ", - upstream_node_id, - node_id); + appendPQExpBuffer(&query, + " SELECT " REPMGR_NODES_COLUMNS + " FROM repmgr.nodes " + " WHERE upstream_node_id = %i " + " AND node_id != %i " + " AND active IS TRUE " + "ORDER BY node_id ", + upstream_node_id, + node_id); log_verbose(LOG_DEBUG, "get_active_sibling_node_records():\n%s", query.data); @@ -2021,16 +2016,15 @@ get_active_sibling_node_records(PGconn *conn, int node_id, int upstream_node_id, void get_node_records_by_priority(PGconn *conn, NodeInfoList *node_list) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT " REPMGR_NODES_COLUMNS - " FROM repmgr.nodes " - "ORDER BY priority DESC, node_name "); + appendPQExpBuffer(&query, + " SELECT " REPMGR_NODES_COLUMNS + " FROM repmgr.nodes " + "ORDER BY priority DESC, node_name "); log_verbose(LOG_DEBUG, "get_node_records_by_priority():\n%s", query.data); @@ -2048,19 +2042,18 @@ get_node_records_by_priority(PGconn *conn, NodeInfoList *node_list) void get_all_node_records_with_upstream(PGconn *conn, NodeInfoList *node_list) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT n.node_id, n.type, n.upstream_node_id, n.node_name, n.conninfo, n.repluser, " - " n.slot_name, n.location, n.priority, n.active, un.node_name AS upstream_node_name " - " FROM repmgr.nodes n " - " LEFT JOIN nodes un " - " ON un.node_id = n.upstream_node_id" - " ORDER BY n.node_id "); + appendPQExpBuffer(&query, + " SELECT n.node_id, n.type, n.upstream_node_id, n.node_name, n.conninfo, n.repluser, " + " n.slot_name, n.location, n.priority, n.active, un.node_name AS upstream_node_name " + " FROM repmgr.nodes n " + " LEFT JOIN nodes un " + " ON un.node_id = n.upstream_node_id" + " ORDER BY n.node_id "); log_verbose(LOG_DEBUG, "get_all_node_records_with_upstream():\n%s", query.data); @@ -2100,19 +2093,19 @@ update_node_record(PGconn *conn, char *repmgr_action, t_node_info *node_info) static bool _create_update_node_record(PGconn *conn, char *action, t_node_info *node_info) { - PQExpBufferData query; - char node_id[MAXLEN] = ""; - char priority[MAXLEN] = ""; + PQExpBufferData query; + char node_id[MAXLEN] = ""; + char priority[MAXLEN] = ""; - char upstream_node_id[MAXLEN] = ""; - char *upstream_node_id_ptr = NULL; + char upstream_node_id[MAXLEN] = ""; + char *upstream_node_id_ptr = NULL; - char *slot_name_ptr = NULL; + char *slot_name_ptr = NULL; - int param_count = 11; - const char *param_values[param_count]; + int param_count = 11; + const char *param_values[param_count]; - PGresult *res; + PGresult *res; maxlen_snprintf(node_id, "%i", node_info->node_id); maxlen_snprintf(priority, "%i", node_info->priority); @@ -2120,10 +2113,11 @@ _create_update_node_record(PGconn *conn, char *action, t_node_info *node_info) if (node_info->upstream_node_id == NO_UPSTREAM_NODE && node_info->type == STANDBY) { /* - * No explicit upstream node id provided for standby - attempt to - * get primary node id + * No explicit upstream node id provided for standby - attempt to get + * primary node id */ - int primary_node_id = get_primary_node_id(conn); + int primary_node_id = get_primary_node_id(conn); + maxlen_snprintf(upstream_node_id, "%i", primary_node_id); upstream_node_id_ptr = upstream_node_id; } @@ -2180,14 +2174,14 @@ _create_update_node_record(PGconn *conn, char *action, t_node_info *node_info) } - res = PQexecParams(conn, - query.data, - param_count, - NULL, - param_values, - NULL, - NULL, - 0); + res = PQexecParams(conn, + query.data, + param_count, + NULL, + param_values, + NULL, + NULL, + 0); termPQExpBuffer(&query); @@ -2209,17 +2203,17 @@ _create_update_node_record(PGconn *conn, char *action, t_node_info *node_info) bool update_node_record_set_active(PGconn *conn, int this_node_id, bool active) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); appendPQExpBuffer( - &query, - "UPDATE repmgr.nodes SET active = %s " - " WHERE node_id = %i", - active == true ? "TRUE" : "FALSE", - this_node_id); + &query, + "UPDATE repmgr.nodes SET active = %s " + " WHERE node_id = %i", + active == true ? "TRUE" : "FALSE", + this_node_id); log_verbose(LOG_DEBUG, "update_node_record_set_active():\n %s", query.data); @@ -2243,7 +2237,7 @@ update_node_record_set_active(PGconn *conn, int this_node_id, bool active) bool update_node_record_set_primary(PGconn *conn, int this_node_id) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; log_debug(_("setting node %i as primary and marking existing primary as failed"), @@ -2289,8 +2283,8 @@ update_node_record_set_primary(PGconn *conn, int this_node_id) if (PQresultStatus(res) != PGRES_COMMAND_OK) { log_error(_("unable to set current node %i as active primary:\n %s"), - this_node_id, - PQerrorMessage(conn)); + this_node_id, + PQerrorMessage(conn)); PQclear(res); rollback_transaction(conn); @@ -2305,7 +2299,7 @@ update_node_record_set_primary(PGconn *conn, int this_node_id) bool update_node_record_set_upstream(PGconn *conn, int this_node_id, int new_upstream_node_id) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; log_debug(_("update_node_record_set_upstream(): Updating node %i's upstream node to %i"), @@ -2327,7 +2321,7 @@ update_node_record_set_upstream(PGconn *conn, int this_node_id, int new_upstream if (PQresultStatus(res) != PGRES_COMMAND_OK) { log_error(_("unable to set new upstream node id:\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); PQclear(res); return false; @@ -2346,7 +2340,7 @@ update_node_record_set_upstream(PGconn *conn, int this_node_id, int new_upstream bool update_node_record_status(PGconn *conn, int this_node_id, char *type, int upstream_node_id, bool active) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); @@ -2370,7 +2364,7 @@ update_node_record_status(PGconn *conn, int this_node_id, char *type, int upstre if (PQresultStatus(res) != PGRES_COMMAND_OK) { log_error(_("unable to update node record:\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); PQclear(res); return false; @@ -2389,20 +2383,19 @@ update_node_record_status(PGconn *conn, int this_node_id, char *type, int upstre bool update_node_record_conn_priority(PGconn *conn, t_configuration_options *options) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "UPDATE repmgr.nodes " - " SET conninfo = '%s', " - " priority = %d " - " WHERE node_id = %d ", - options->conninfo, - options->priority, - options->node_id); + appendPQExpBuffer(&query, + "UPDATE repmgr.nodes " + " SET conninfo = '%s', " + " priority = %d " + " WHERE node_id = %d ", + options->conninfo, + options->priority, + options->node_id); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -2422,7 +2415,7 @@ update_node_record_conn_priority(PGconn *conn, t_configuration_options *options) bool delete_node_record(PGconn *conn, int node) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); @@ -2440,7 +2433,7 @@ delete_node_record(PGconn *conn, int node) if (PQresultStatus(res) != PGRES_COMMAND_OK) { log_error(_("unable to delete node record:\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); PQclear(res); return false; } @@ -2454,20 +2447,19 @@ delete_node_record(PGconn *conn, int node) void get_node_replication_stats(PGconn *conn, t_node_info *node_info) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT current_setting('max_wal_senders')::INT AS max_wal_senders, " - " (SELECT COUNT(*) FROM pg_catalog.pg_stat_replication) AS attached_wal_receivers, " - " current_setting('max_replication_slots')::INT AS max_replication_slots, " - " (SELECT COUNT(*) FROM pg_catalog.pg_replication_slots) AS total_replication_slots, " - " (SELECT COUNT(*) FROM pg_catalog.pg_replication_slots WHERE active = TRUE) AS active_replication_slots, " - " (SELECT COUNT(*) FROM pg_catalog.pg_replication_slots WHERE active = FALSE) AS inactive_replication_slots, " - " pg_catalog.pg_is_in_recovery() AS in_recovery"); + appendPQExpBuffer(&query, + " SELECT current_setting('max_wal_senders')::INT AS max_wal_senders, " + " (SELECT COUNT(*) FROM pg_catalog.pg_stat_replication) AS attached_wal_receivers, " + " current_setting('max_replication_slots')::INT AS max_replication_slots, " + " (SELECT COUNT(*) FROM pg_catalog.pg_replication_slots) AS total_replication_slots, " + " (SELECT COUNT(*) FROM pg_catalog.pg_replication_slots WHERE active = TRUE) AS active_replication_slots, " + " (SELECT COUNT(*) FROM pg_catalog.pg_replication_slots WHERE active = FALSE) AS inactive_replication_slots, " + " pg_catalog.pg_is_in_recovery() AS in_recovery"); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -2497,17 +2489,16 @@ get_node_replication_stats(PGconn *conn, t_node_info *node_info) bool is_downstream_node_attached(PGconn *conn, char *node_name) { - PQExpBufferData query; - PGresult *res = NULL; - int c = 0; + PQExpBufferData query; + PGresult *res = NULL; + int c = 0; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT COUNT(*) FROM pg_catalog.pg_stat_replication " - " WHERE application_name = '%s'", - node_name); + appendPQExpBuffer(&query, + " SELECT COUNT(*) FROM pg_catalog.pg_stat_replication " + " WHERE application_name = '%s'", + node_name); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -2586,33 +2577,32 @@ clear_node_info_list(NodeInfoList *nodes) bool get_datadir_configuration_files(PGconn *conn, KeyValueList *list) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; - int i; + int i; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "WITH files AS ( " - " WITH dd AS ( " - " SELECT setting " - " FROM pg_catalog.pg_settings " - " WHERE name = 'data_directory') " - " SELECT distinct(sourcefile) AS config_file" - " FROM dd, pg_catalog.pg_settings ps " - " WHERE ps.sourcefile IS NOT NULL " - " AND ps.sourcefile ~ ('^' || dd.setting) " - " UNION " - " SELECT ps.setting AS config_file" - " FROM dd, pg_catalog.pg_settings ps " - " WHERE ps.name IN ( 'config_file', 'hba_file', 'ident_file') " - " AND ps.setting ~ ('^' || dd.setting) " - ") " - " SELECT config_file, " - " regexp_replace(config_file, '^.*\\/','') AS filename " - " FROM files " - "ORDER BY config_file"); + appendPQExpBuffer(&query, + "WITH files AS ( " + " WITH dd AS ( " + " SELECT setting " + " FROM pg_catalog.pg_settings " + " WHERE name = 'data_directory') " + " SELECT distinct(sourcefile) AS config_file" + " FROM dd, pg_catalog.pg_settings ps " + " WHERE ps.sourcefile IS NOT NULL " + " AND ps.sourcefile ~ ('^' || dd.setting) " + " UNION " + " SELECT ps.setting AS config_file" + " FROM dd, pg_catalog.pg_settings ps " + " WHERE ps.name IN ( 'config_file', 'hba_file', 'ident_file') " + " AND ps.setting ~ ('^' || dd.setting) " + ") " + " SELECT config_file, " + " regexp_replace(config_file, '^.*\\/','') AS filename " + " FROM files " + "ORDER BY config_file"); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -2628,9 +2618,9 @@ get_datadir_configuration_files(PGconn *conn, KeyValueList *list) for (i = 0; i < PQntuples(res); i++) { key_value_list_set( - list, - PQgetvalue(res, i, 1), - PQgetvalue(res, i, 0)); + list, + PQgetvalue(res, i, 1), + PQgetvalue(res, i, 0)); } PQclear(res); @@ -2641,25 +2631,24 @@ get_datadir_configuration_files(PGconn *conn, KeyValueList *list) bool get_configuration_file_locations(PGconn *conn, t_configfile_list *list) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; - int i; + int i; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " WITH dd AS ( " - " SELECT setting AS data_directory" - " FROM pg_catalog.pg_settings " - " WHERE name = 'data_directory' " - " ) " - " SELECT DISTINCT(sourcefile), " - " pg_catalog.regexp_replace(sourcefile, '^.*\\/', '') AS filename, " - " sourcefile ~ ('^' || dd.data_directory) AS in_data_dir " - " FROM dd, pg_catalog.pg_settings ps " - " WHERE sourcefile IS NOT NULL " - " ORDER BY 1 "); + appendPQExpBuffer(&query, + " WITH dd AS ( " + " SELECT setting AS data_directory" + " FROM pg_catalog.pg_settings " + " WHERE name = 'data_directory' " + " ) " + " SELECT DISTINCT(sourcefile), " + " pg_catalog.regexp_replace(sourcefile, '^.*\\/', '') AS filename, " + " sourcefile ~ ('^' || dd.data_directory) AS in_data_dir " + " FROM dd, pg_catalog.pg_settings ps " + " WHERE sourcefile IS NOT NULL " + " ORDER BY 1 "); log_verbose(LOG_DEBUG, "get_configuration_file_locations():\n %s", query.data); @@ -2697,19 +2686,18 @@ get_configuration_file_locations(PGconn *conn, t_configfile_list *list) /* Fetch locations of pg_hba.conf and pg_ident.conf */ initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " WITH dd AS ( " - " SELECT setting AS data_directory" - " FROM pg_catalog.pg_settings " - " WHERE name = 'data_directory' " - " ) " - " SELECT ps.setting, " - " regexp_replace(setting, '^.*\\/', '') AS filename, " - " ps.setting ~ ('^' || dd.data_directory) AS in_data_dir " - " FROM dd, pg_catalog.pg_settings ps " - " WHERE ps.name IN ('hba_file', 'ident_file') " - " ORDER BY 1 "); + appendPQExpBuffer(&query, + " WITH dd AS ( " + " SELECT setting AS data_directory" + " FROM pg_catalog.pg_settings " + " WHERE name = 'data_directory' " + " ) " + " SELECT ps.setting, " + " regexp_replace(setting, '^.*\\/', '') AS filename, " + " ps.setting ~ ('^' || dd.data_directory) AS in_data_dir " + " FROM dd, pg_catalog.pg_settings ps " + " WHERE ps.name IN ('hba_file', 'ident_file') " + " ORDER BY 1 "); log_verbose(LOG_DEBUG, "get_configuration_file_locations():\n %s", @@ -2731,10 +2719,10 @@ get_configuration_file_locations(PGconn *conn, t_configfile_list *list) for (i = 0; i < PQntuples(res); i++) { config_file_list_add( - list, - PQgetvalue(res, i, 0), - PQgetvalue(res, i, 1), - atobool(PQgetvalue(res, i, 2))); + list, + PQgetvalue(res, i, 0), + PQgetvalue(res, i, 1), + atobool(PQgetvalue(res, i, 2))); } PQclear(res); @@ -2781,7 +2769,7 @@ config_file_list_add(t_configfile_list *list, const char *file, const char *file strncpy(list->files[list->entries]->filename, filename, MAXPGPATH); list->files[list->entries]->in_data_directory = in_data_dir; - list->entries ++; + list->entries++; } @@ -2851,7 +2839,7 @@ create_event_notification_extended(PGconn *conn, t_configuration_options *option static bool _create_event(PGconn *conn, t_configuration_options *options, int node_id, char *event, bool successful, char *details, t_event_info *event_info, bool send_notification) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; char event_timestamp[MAXLEN] = ""; bool success = true; @@ -2860,26 +2848,27 @@ _create_event(PGconn *conn, t_configuration_options *options, int node_id, char * Only attempt to write a record if a connection handle was provided. * Also check that the repmgr schema has been properly initialised - if * not it means no configuration file was provided, which can happen with - * e.g. `repmgr standby clone`, and we won't know which schema to write to. + * e.g. `repmgr standby clone`, and we won't know which schema to write + * to. */ if (conn != NULL && PQstatus(conn) == CONNECTION_OK) { - int n_node_id = htonl(node_id); - char *t_successful = successful ? "TRUE" : "FALSE"; + int n_node_id = htonl(node_id); + char *t_successful = successful ? "TRUE" : "FALSE"; - const char *values[4] = { (char *)&n_node_id, - event, - t_successful, - details - }; + const char *values[4] = {(char *) &n_node_id, + event, + t_successful, + details + }; - int lengths[4] = { sizeof(n_node_id), - 0, - 0, - 0 - }; + int lengths[4] = {sizeof(n_node_id), + 0, + 0, + 0 + }; - int binary[4] = {1, 0, 0, 0}; + int binary[4] = {1, 0, 0, 0}; initPQExpBuffer(&query); appendPQExpBuffer(&query, @@ -2924,12 +2913,12 @@ _create_event(PGconn *conn, t_configuration_options *options, int node_id, char /* * If no database connection provided, or the query failed, generate a - * current timestamp ourselves. This isn't quite the same - * format as PostgreSQL, but is close enough for diagnostic use. + * current timestamp ourselves. This isn't quite the same format as + * PostgreSQL, but is close enough for diagnostic use. */ if (!strlen(event_timestamp)) { - time_t now; + time_t now; struct tm ts; time(&now); @@ -2946,12 +2935,12 @@ _create_event(PGconn *conn, t_configuration_options *options, int node_id, char const char *src_ptr = NULL; char *dst_ptr = NULL; char *end_ptr = NULL; - int r = 0; + int r = 0; /* - * If configuration option 'event_notifications' was provided, - * check if this event is one of the ones listed; if not listed, - * don't execute the notification script. + * If configuration option 'event_notifications' was provided, check + * if this event is one of the ones listed; if not listed, don't + * execute the notification script. * * (If 'event_notifications' was not provided, we assume the script * should be executed for all events). @@ -2959,7 +2948,7 @@ _create_event(PGconn *conn, t_configuration_options *options, int node_id, char if (options->event_notifications.head != NULL) { EventNotificationListCell *cell = NULL; - bool notify_ok = false; + bool notify_ok = false; for (cell = options->event_notifications.head; cell; cell = cell->next) { @@ -2971,7 +2960,8 @@ _create_event(PGconn *conn, t_configuration_options *options, int node_id, char } /* - * Event type not found in the 'event_notifications' list - return early + * Event type not found in the 'event_notifications' list - return + * early */ if (notify_ok == false) { @@ -2984,7 +2974,7 @@ _create_event(PGconn *conn, t_configuration_options *options, int node_id, char end_ptr = parsed_command + MAXPGPATH - 1; *end_ptr = '\0'; - for(src_ptr = options->event_notification_command; *src_ptr; src_ptr++) + for (src_ptr = options->event_notification_command; *src_ptr; src_ptr++) { if (*src_ptr == '%') { @@ -3092,15 +3082,15 @@ _create_event(PGconn *conn, t_configuration_options *options, int node_id, char bool create_replication_slot(PGconn *conn, char *slot_name, int server_version_num, PQExpBufferData *error_msg) { - PQExpBufferData query; - RecordStatus record_status = RECORD_NOT_FOUND; - PGresult *res = NULL; - t_replication_slot slot_info = T_REPLICATION_SLOT_INITIALIZER; + PQExpBufferData query; + RecordStatus record_status = RECORD_NOT_FOUND; + PGresult *res = NULL; + t_replication_slot slot_info = T_REPLICATION_SLOT_INITIALIZER; /* * Check whether slot exists already; if it exists and is active, that - * means another active standby is using it, which creates an error situation; - * if not we can reuse it as-is + * means another active standby is using it, which creates an error + * situation; if not we can reuse it as-is */ record_status = get_slot_record(conn, slot_name, &slot_info); @@ -3117,7 +3107,7 @@ create_replication_slot(PGconn *conn, char *slot_name, int server_version_num, P if (slot_info.active == false) { - // XXX is this a good idea? + /* XXX is this a good idea? */ log_debug("replication slot \"%s\" exists but is inactive; reusing", slot_name); @@ -3170,7 +3160,7 @@ create_replication_slot(PGconn *conn, char *slot_name, int server_version_num, P bool drop_replication_slot(PGconn *conn, char *slot_name) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); @@ -3206,14 +3196,14 @@ drop_replication_slot(PGconn *conn, char *slot_name) RecordStatus get_slot_record(PGconn *conn, char *slot_name, t_replication_slot *record) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); appendPQExpBuffer(&query, "SELECT slot_name, slot_type, active " - " FROM pg_catalog.pg_replication_slots " + " FROM pg_catalog.pg_replication_slots " " WHERE slot_name = '%s' ", slot_name); @@ -3226,7 +3216,7 @@ get_slot_record(PGconn *conn, char *slot_name, t_replication_slot *record) if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_error(_("unable to query pg_replication_slots:\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); PQclear(res); return RECORD_ERROR; } @@ -3253,17 +3243,17 @@ get_slot_record(PGconn *conn, char *slot_name, t_replication_slot *record) bool get_tablespace_name_by_location(PGconn *conn, const char *location, char *name) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); appendPQExpBuffer( - &query, - "SELECT spcname " - " FROM pg_catalog.pg_tablespace " - " WHERE pg_catalog.pg_tablespace_location(oid) = '%s'", - location); + &query, + "SELECT spcname " + " FROM pg_catalog.pg_tablespace " + " WHERE pg_catalog.pg_tablespace_location(oid) = '%s'", + location); log_verbose(LOG_DEBUG, "get_tablespace_name_by_location():\n%s", query.data); @@ -3404,7 +3394,7 @@ wait_connection_availability(PGconn *conn, long long timeout) bool is_server_available(const char *conninfo) { - PGPing status = PQping(conninfo); + PGPing status = PQping(conninfo); if (status == PQPING_OK) return true; @@ -3419,49 +3409,48 @@ is_server_available(const char *conninfo) void add_monitoring_record( - PGconn *primary_conn, - PGconn *local_conn, - int primary_node_id, - int local_node_id, - char *monitor_standby_timestamp, - XLogRecPtr primary_last_wal_location, - XLogRecPtr last_wal_receive_lsn, - char *last_xact_replay_timestamp, - long long unsigned int replication_lag_bytes, - long long unsigned int apply_lag_bytes - ) + PGconn *primary_conn, + PGconn *local_conn, + int primary_node_id, + int local_node_id, + char *monitor_standby_timestamp, + XLogRecPtr primary_last_wal_location, + XLogRecPtr last_wal_receive_lsn, + char *last_xact_replay_timestamp, + long long unsigned int replication_lag_bytes, + long long unsigned int apply_lag_bytes +) { - PQExpBufferData query; + PQExpBufferData query; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "INSERT INTO repmgr.monitoring_history " - " (primary_node_id, " - " standby_node_id, " - " last_monitor_time, " - " last_apply_time, " - " last_wal_primary_location, " - " last_wal_standby_location, " - " replication_lag, " - " apply_lag ) " - " VALUES(%i, " - " %i, " - " '%s'::TIMESTAMP WITH TIME ZONE, " - " '%s'::TIMESTAMP WITH TIME ZONE, " - " '%X/%X', " - " '%X/%X', " - " %llu, " - " %llu) ", - primary_node_id, - local_node_id, - monitor_standby_timestamp, - last_xact_replay_timestamp, - format_lsn(primary_last_wal_location), - format_lsn(last_wal_receive_lsn), - replication_lag_bytes, - apply_lag_bytes); + appendPQExpBuffer(&query, + "INSERT INTO repmgr.monitoring_history " + " (primary_node_id, " + " standby_node_id, " + " last_monitor_time, " + " last_apply_time, " + " last_wal_primary_location, " + " last_wal_standby_location, " + " replication_lag, " + " apply_lag ) " + " VALUES(%i, " + " %i, " + " '%s'::TIMESTAMP WITH TIME ZONE, " + " '%s'::TIMESTAMP WITH TIME ZONE, " + " '%X/%X', " + " '%X/%X', " + " %llu, " + " %llu) ", + primary_node_id, + local_node_id, + monitor_standby_timestamp, + last_xact_replay_timestamp, + format_lsn(primary_last_wal_location), + format_lsn(last_wal_receive_lsn), + replication_lag_bytes, + apply_lag_bytes); log_verbose(LOG_DEBUG, "standby_monitor:()\n%s", query.data); @@ -3472,11 +3461,11 @@ add_monitoring_record( } else { - PGresult *res = NULL; + PGresult *res = NULL; res = PQexec(local_conn, "SELECT repmgr.standby_set_last_updated()"); - /* not critical if the above query fails*/ + /* not critical if the above query fails */ if (PQresultStatus(res) != PGRES_TUPLES_OK) log_warning(_("unable to set last_updated:\n %s"), PQerrorMessage(local_conn)); @@ -3498,15 +3487,15 @@ add_monitoring_record( NodeVotingStatus get_voting_status(PGconn *conn) { - PGresult *res = NULL; - NodeVotingStatus voting_status = VS_UNKNOWN; + PGresult *res = NULL; + NodeVotingStatus voting_status = VS_UNKNOWN; res = PQexec(conn, "SELECT repmgr.get_voting_status()"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_error(_("unable to query repmgr.get_voting_status():\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); PQclear(res); return VS_UNKNOWN; } @@ -3521,9 +3510,9 @@ get_voting_status(PGconn *conn) VoteRequestResult request_vote(PGconn *conn, t_node_info *this_node, t_node_info *other_node, int electoral_term) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; - int lsn_diff = 0; + int lsn_diff = 0; other_node->last_wal_receive_lsn = InvalidXLogRecPtr; @@ -3549,23 +3538,21 @@ request_vote(PGconn *conn, t_node_info *this_node, t_node_info *other_node, int log_debug("NULL returned by repmgr.request_vote()"); /* - * get the node's last receive location anyway - * TODO: have repmgr.request_vote() return two values + * get the node's last receive location anyway TODO: have + * repmgr.request_vote() return two values */ initPQExpBuffer(&query); if (server_version_num >= 100000) { - appendPQExpBuffer( - &query, - "SELECT pg_catalog.pg_last_wal_receive_lsn()"); + appendPQExpBuffer(&query, + "SELECT pg_catalog.pg_last_wal_receive_lsn()"); } else { - appendPQExpBuffer( - &query, - "SELECT pg_catalog.pg_last_xlog_receive_location()"); + appendPQExpBuffer(&query, + "SELECT pg_catalog.pg_last_xlog_receive_location()"); } res = PQexec(conn, query.data); @@ -3623,8 +3610,8 @@ request_vote(PGconn *conn, t_node_info *this_node, t_node_info *other_node, int int set_voting_status_initiated(PGconn *conn) { - PGresult *res = NULL; - int electoral_term = 0; + PGresult *res = NULL; + int electoral_term = 0; res = PQexec(conn, "SELECT repmgr.set_voting_status_initiated()"); @@ -3639,10 +3626,10 @@ set_voting_status_initiated(PGconn *conn) bool announce_candidature(PGconn *conn, t_node_info *this_node, t_node_info *other_node, int electoral_term) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; - bool retval = false; + bool retval = false; initPQExpBuffer(&query); @@ -3665,7 +3652,7 @@ announce_candidature(PGconn *conn, t_node_info *this_node, t_node_info *other_no void notify_follow_primary(PGconn *conn, int primary_node_id) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; @@ -3676,14 +3663,14 @@ notify_follow_primary(PGconn *conn, int primary_node_id) primary_node_id); log_verbose(LOG_DEBUG, "notify_follow_primary():\n %s", query.data); - // XXX handle failure + /* XXX handle failure */ res = PQexec(conn, query.data); termPQExpBuffer(&query); if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_error(_("unable to execute repmgr.notify_follow_primary():\n %s"), - PQerrorMessage(conn)); + PQerrorMessage(conn)); } PQclear(res); @@ -3694,10 +3681,10 @@ notify_follow_primary(PGconn *conn, int primary_node_id) bool get_new_primary(PGconn *conn, int *primary_node_id) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; - int new_primary_node_id = UNKNOWN_NODE_ID; + int new_primary_node_id = UNKNOWN_NODE_ID; initPQExpBuffer(&query); @@ -3706,7 +3693,7 @@ get_new_primary(PGconn *conn, int *primary_node_id) res = PQexec(conn, query.data); termPQExpBuffer(&query); - // XXX handle error + /* XXX handle error */ new_primary_node_id = atoi(PQgetvalue(res, 0, 0)); @@ -3727,7 +3714,7 @@ get_new_primary(PGconn *conn, int *primary_node_id) void reset_voting_status(PGconn *conn) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; initPQExpBuffer(&query); @@ -3738,7 +3725,7 @@ reset_voting_status(PGconn *conn) res = PQexec(conn, query.data); termPQExpBuffer(&query); - // COMMAND_OK? + /* COMMAND_OK? */ if (PQresultStatus(res) != PGRES_TUPLES_OK) { log_error(_("unable to execute repmgr.reset_voting_status():\n %s"), @@ -3758,8 +3745,8 @@ reset_voting_status(PGconn *conn) XLogRecPtr get_current_wal_lsn(PGconn *conn) { - PGresult *res = NULL; - XLogRecPtr ptr = InvalidXLogRecPtr; + PGresult *res = NULL; + XLogRecPtr ptr = InvalidXLogRecPtr; if (server_version_num >= 100000) @@ -3784,8 +3771,8 @@ get_current_wal_lsn(PGconn *conn) XLogRecPtr get_last_wal_receive_location(PGconn *conn) { - PGresult *res = NULL; - XLogRecPtr ptr = InvalidXLogRecPtr; + PGresult *res = NULL; + XLogRecPtr ptr = InvalidXLogRecPtr; if (server_version_num >= 100000) @@ -3814,15 +3801,14 @@ get_last_wal_receive_location(PGconn *conn) bool is_bdr_db(PGconn *conn, PQExpBufferData *output) { - PQExpBufferData query; - PGresult *res = NULL; - bool is_bdr_db = false; + PQExpBufferData query; + PGresult *res = NULL; + bool is_bdr_db = false; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "SELECT COUNT(*) FROM pg_catalog.pg_extension WHERE extname='bdr'"); + appendPQExpBuffer(&query, + "SELECT COUNT(*) FROM pg_catalog.pg_extension WHERE extname='bdr'"); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -3852,9 +3838,8 @@ is_bdr_db(PGconn *conn, PQExpBufferData *output) initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "SELECT bdr.bdr_is_active_in_db()"); + appendPQExpBuffer(&query, + "SELECT bdr.bdr_is_active_in_db()"); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -3879,19 +3864,18 @@ is_bdr_db(PGconn *conn, PQExpBufferData *output) bool is_active_bdr_node(PGconn *conn, const char *node_name) { - PQExpBufferData query; - PGresult *res = NULL; - bool is_active_bdr_node = false; + PQExpBufferData query; + PGresult *res = NULL; + bool is_active_bdr_node = false; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT COALESCE(s.active, TRUE) AS active" - " FROM bdr.bdr_nodes n " - " LEFT JOIN pg_replication_slots s " - " ON slot_name=bdr.bdr_format_slot_name(n.node_sysid, n.node_timeline, n.node_dboid, (SELECT oid FROM pg_database WHERE datname = current_database())) " - " WHERE node_name='%s' ", - node_name); + appendPQExpBuffer(&query, + " SELECT COALESCE(s.active, TRUE) AS active" + " FROM bdr.bdr_nodes n " + " LEFT JOIN pg_replication_slots s " + " ON slot_name=bdr.bdr_format_slot_name(n.node_sysid, n.node_timeline, n.node_dboid, (SELECT oid FROM pg_database WHERE datname = current_database())) " + " WHERE node_name='%s' ", + node_name); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -3914,17 +3898,16 @@ is_active_bdr_node(PGconn *conn, const char *node_name) bool is_bdr_repmgr(PGconn *conn) { - PQExpBufferData query; + PQExpBufferData query; PGresult *res = NULL; - int non_bdr_nodes = 0; + int non_bdr_nodes = 0; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "SELECT COUNT(*)" - " FROM repmgr.nodes" - " WHERE type != 'bdr' "); + appendPQExpBuffer(&query, + "SELECT COUNT(*)" + " FROM repmgr.nodes" + " WHERE type != 'bdr' "); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -3946,19 +3929,18 @@ is_bdr_repmgr(PGconn *conn) bool is_table_in_bdr_replication_set(PGconn *conn, const char *tablename, const char *set) { - PQExpBufferData query; - PGresult *res = NULL; - bool in_replication_set = false; + PQExpBufferData query; + PGresult *res = NULL; + bool in_replication_set = false; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "SELECT COUNT(*) " - " FROM UNNEST(bdr.table_get_replication_sets('repmgr.%s')) AS repset " - " WHERE repset='%s' ", - tablename, - set); + appendPQExpBuffer(&query, + "SELECT COUNT(*) " + " FROM UNNEST(bdr.table_get_replication_sets('repmgr.%s')) AS repset " + " WHERE repset='%s' ", + tablename, + set); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -3982,16 +3964,15 @@ is_table_in_bdr_replication_set(PGconn *conn, const char *tablename, const char bool add_table_to_bdr_replication_set(PGconn *conn, const char *tablename, const char *set) { - PQExpBufferData query; - PGresult *res = NULL; + PQExpBufferData query; + PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "SELECT bdr.table_set_replication_sets('repmgr.%s', '{%s}')", - tablename, - set); + appendPQExpBuffer(&query, + "SELECT bdr.table_set_replication_sets('repmgr.%s', '{%s}')", + tablename, + set); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -4017,18 +3998,17 @@ add_table_to_bdr_replication_set(PGconn *conn, const char *tablename, const char bool bdr_node_exists(PGconn *conn, const char *node_name) { - PQExpBufferData query; - PGresult *res = NULL; - bool node_exists = false; + PQExpBufferData query; + PGresult *res = NULL; + bool node_exists = false; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "SELECT COUNT(*)" - " FROM bdr.bdr_nodes" - " WHERE node_name = '%s'", - node_name); + appendPQExpBuffer(&query, + "SELECT COUNT(*)" + " FROM bdr.bdr_nodes" + " WHERE node_name = '%s'", + node_name); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -4051,21 +4031,20 @@ bdr_node_exists(PGconn *conn, const char *node_name) ReplSlotStatus get_bdr_node_replication_slot_status(PGconn *conn, const char *node_name) { - PQExpBufferData query; - PGresult *res = NULL; - ReplSlotStatus status = SLOT_UNKNOWN; + PQExpBufferData query; + PGresult *res = NULL; + ReplSlotStatus status = SLOT_UNKNOWN; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT s.active " - " FROM pg_catalog.pg_replication_slots s " - " WHERE slot_name = " - " (SELECT bdr.bdr_format_slot_name(node_sysid, node_timeline, node_dboid, datoid) " - " FROM bdr.bdr_nodes " - " WHERE node_name = '%s') ", - node_name); + appendPQExpBuffer(&query, + " SELECT s.active " + " FROM pg_catalog.pg_replication_slots s " + " WHERE slot_name = " + " (SELECT bdr.bdr_format_slot_name(node_sysid, node_timeline, node_dboid, datoid) " + " FROM bdr.bdr_nodes " + " WHERE node_name = '%s') ", + node_name); log_verbose(LOG_DEBUG, "get_bdr_node_replication_slot_status():\n %s", query.data); @@ -4092,24 +4071,23 @@ get_bdr_node_replication_slot_status(PGconn *conn, const char *node_name) void get_bdr_other_node_name(PGconn *conn, int node_id, char *node_name) { - PQExpBufferData query; - PGresult *res = NULL; + PQExpBufferData query; + PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT node_name " - " FROM repmgr.nodes " - " WHERE node_id != %i", - node_id); + appendPQExpBuffer(&query, + " SELECT node_name " + " FROM repmgr.nodes " + " WHERE node_id != %i", + node_id); log_verbose(LOG_DEBUG, "get_bdr_other_node_name():\n %s", query.data); res = PQexec(conn, query.data); termPQExpBuffer(&query); - if(PQresultStatus(res) == PGRES_TUPLES_OK) + if (PQresultStatus(res) == PGRES_TUPLES_OK) { strncpy(node_name, PQgetvalue(res, 0, 0), MAXLEN); } @@ -4127,37 +4105,36 @@ get_bdr_other_node_name(PGconn *conn, int node_id, char *node_name) void add_extension_tables_to_bdr_replication_set(PGconn *conn) { - PQExpBufferData query; - PGresult *res = NULL; + PQExpBufferData query; + PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT c.relname " - " FROM pg_class c " - "INNER JOIN pg_namespace n " - " ON c.relnamespace = n.oid " - " WHERE n.nspname = 'repmgr' " - " AND c.relkind = 'r' "); + appendPQExpBuffer(&query, + " SELECT c.relname " + " FROM pg_class c " + "INNER JOIN pg_namespace n " + " ON c.relnamespace = n.oid " + " WHERE n.nspname = 'repmgr' " + " AND c.relkind = 'r' "); res = PQexec(conn, query.data); termPQExpBuffer(&query); if (PQresultStatus(res) != PGRES_TUPLES_OK) { - // + /* */ } else { - int i; + int i; for (i = 0; i < PQntuples(res); i++) { add_table_to_bdr_replication_set( - conn, - PQgetvalue(res, i, 0), - "repmgr"); + conn, + PQgetvalue(res, i, 0), + "repmgr"); } } @@ -4169,16 +4146,15 @@ add_extension_tables_to_bdr_replication_set(PGconn *conn) void get_all_bdr_node_records(PGconn *conn, BdrNodeInfoList *node_list) { - PQExpBufferData query; - PGresult *res = NULL; + PQExpBufferData query; + PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT " BDR_NODES_COLUMNS - " FROM bdr.bdr_nodes " - "ORDER BY node_seq_id "); + appendPQExpBuffer(&query, + " SELECT " BDR_NODES_COLUMNS + " FROM bdr.bdr_nodes " + "ORDER BY node_seq_id "); log_verbose(LOG_DEBUG, "get_all_node_records():\n%s", query.data); @@ -4194,17 +4170,16 @@ get_all_bdr_node_records(PGconn *conn, BdrNodeInfoList *node_list) RecordStatus get_bdr_node_record_by_name(PGconn *conn, const char *node_name, t_bdr_node_info *node_info) { - PQExpBufferData query; - PGresult *res = NULL; + PQExpBufferData query; + PGresult *res = NULL; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - " SELECT " BDR_NODES_COLUMNS - " FROM bdr.bdr_nodes " - " WHERE node_name = '%s'", - node_name); + appendPQExpBuffer(&query, + " SELECT " BDR_NODES_COLUMNS + " FROM bdr.bdr_nodes " + " WHERE node_name = '%s'", + node_name); log_verbose(LOG_DEBUG, "get_bdr_node_record_by_name():\n%s", query.data); @@ -4236,11 +4211,12 @@ get_bdr_node_record_by_name(PGconn *conn, const char *node_name, t_bdr_node_info static -void _populate_bdr_node_records(PGresult *res, BdrNodeInfoList *node_list) +void +_populate_bdr_node_records(PGresult *res, BdrNodeInfoList *node_list) { - int i; + int i; - clear_node_info_list((NodeInfoList *)node_list); + clear_node_info_list((NodeInfoList *) node_list); if (PQresultStatus(res) != PGRES_TUPLES_OK) { @@ -4250,6 +4226,7 @@ void _populate_bdr_node_records(PGresult *res, BdrNodeInfoList *node_list) for (i = 0; i < PQntuples(res); i++) { BdrNodeInfoListCell *cell; + cell = (BdrNodeInfoListCell *) pg_malloc0(sizeof(BdrNodeInfoListCell)); cell->node_info = pg_malloc0(sizeof(t_bdr_node_info)); @@ -4272,7 +4249,7 @@ void _populate_bdr_node_records(PGresult *res, BdrNodeInfoList *node_list) static void _populate_bdr_node_record(PGresult *res, t_bdr_node_info *node_info, int row) { - char buf[MAXLEN] = ""; + char buf[MAXLEN] = ""; strncpy(node_info->node_sysid, PQgetvalue(res, row, 0), MAXLEN); node_info->node_timeline = atoi(PQgetvalue(res, row, 1)); @@ -4288,16 +4265,15 @@ _populate_bdr_node_record(PGresult *res, t_bdr_node_info *node_info, int row) bool am_bdr_failover_handler(PGconn *conn, int node_id) { - PQExpBufferData query; - PGresult *res = NULL; - bool am_handler = false; + PQExpBufferData query; + PGresult *res = NULL; + bool am_handler = false; initPQExpBuffer(&query); - appendPQExpBuffer( - &query, - "SELECT repmgr.am_bdr_failover_handler(%i)", - node_id); + appendPQExpBuffer(&query, + "SELECT repmgr.am_bdr_failover_handler(%i)", + node_id); res = PQexec(conn, query.data); termPQExpBuffer(&query); @@ -4321,10 +4297,10 @@ am_bdr_failover_handler(PGconn *conn, int node_id) void unset_bdr_failover_handler(PGconn *conn) { - PGresult *res = NULL; + PGresult *res = NULL; + res = PQexec(conn, "SELECT repmgr.unset_bdr_failover_handler()"); PQclear(res); return; } - diff --git a/dbutils.h b/dbutils.h index ac633316..4fc63478 100644 --- a/dbutils.h +++ b/dbutils.h @@ -33,52 +33,60 @@ #define ERRBUFF_SIZE 512 -typedef enum { +typedef enum +{ UNKNOWN = 0, PRIMARY, STANDBY, BDR } t_server_type; -typedef enum { +typedef enum +{ REPMGR_INSTALLED = 0, REPMGR_AVAILABLE, REPMGR_UNAVAILABLE, - REPMGR_UNKNOWN + REPMGR_UNKNOWN } ExtensionStatus; -typedef enum { +typedef enum +{ RECTYPE_UNKNOWN = -1, RECTYPE_PRIMARY, RECTYPE_STANDBY } RecoveryType; -typedef enum { +typedef enum +{ RECORD_ERROR = -1, RECORD_FOUND, RECORD_NOT_FOUND } RecordStatus; -typedef enum { +typedef enum +{ MS_NORMAL = 0, MS_DEGRADED = 1 } MonitoringState; -typedef enum { +typedef enum +{ NODE_STATUS_UNKNOWN = -1, NODE_STATUS_UP, NODE_STATUS_DOWN, NODE_STATUS_UNCLEAN_SHUTDOWN } NodeStatus; -typedef enum { +typedef enum +{ VR_VOTE_REFUSED = -1, VR_POSITIVE_VOTE, VR_NEGATIVE_VOTE } VoteRequestResult; -typedef enum { +typedef enum +{ SLOT_UNKNOWN = -1, SLOT_INACTIVE, SLOT_ACTIVE @@ -90,36 +98,36 @@ typedef enum { typedef struct s_node_info { /* contents of "repmgr.nodes" */ - int node_id; - int upstream_node_id; + int node_id; + int upstream_node_id; t_server_type type; - char node_name[MAXLEN]; - char upstream_node_name[MAXLEN]; - char conninfo[MAXLEN]; - char repluser[NAMEDATALEN]; - char location[MAXLEN]; - int priority; - bool active; - char slot_name[MAXLEN]; - char config_file[MAXPGPATH]; + char node_name[MAXLEN]; + char upstream_node_name[MAXLEN]; + char conninfo[MAXLEN]; + char repluser[NAMEDATALEN]; + char location[MAXLEN]; + int priority; + bool active; + char slot_name[MAXLEN]; + char config_file[MAXPGPATH]; /* used during failover to track node status */ - XLogRecPtr last_wal_receive_lsn; - NodeStatus node_status; - RecoveryType recovery_type; + XLogRecPtr last_wal_receive_lsn; + NodeStatus node_status; + RecoveryType recovery_type; MonitoringState monitoring_state; - PGconn *conn; + PGconn *conn; /* for ad-hoc use e.g. when working with a list of nodes */ - char details[MAXLEN]; - bool reachable; - bool attached; + char details[MAXLEN]; + bool reachable; + bool attached; /* various statistics */ - int max_wal_senders; - int attached_wal_receivers; - int max_replication_slots; - int total_replication_slots; - int active_replication_slots; - int inactive_replication_slots; -} t_node_info; + int max_wal_senders; + int attached_wal_receivers; + int max_replication_slots; + int total_replication_slots; + int active_replication_slots; + int inactive_replication_slots; +} t_node_info; #define T_NODE_INFO_INITIALIZER { \ @@ -160,7 +168,7 @@ typedef struct NodeInfoList { NodeInfoListCell *head; NodeInfoListCell *tail; - int node_count; + int node_count; } NodeInfoList; #define T_NODE_INFO_LIST_INITIALIZER { \ @@ -171,9 +179,9 @@ typedef struct NodeInfoList typedef struct s_event_info { - char *node_name; - char *conninfo_str; -} t_event_info; + char *node_name; + char *conninfo_str; +} t_event_info; #define T_EVENT_INFO_INITIALIZER { \ NULL, \ @@ -186,9 +194,9 @@ typedef struct s_event_info */ typedef struct { - int size; - char **keywords; - char **values; + int size; + char **keywords; + char **values; } t_conninfo_param_list; #define T_CONNINFO_PARAM_LIST_INITIALIZER { \ @@ -202,19 +210,19 @@ typedef struct */ typedef struct s_replication_slot { - char slot_name[MAXLEN]; - char slot_type[MAXLEN]; - bool active; -} t_replication_slot; + char slot_name[MAXLEN]; + char slot_type[MAXLEN]; + bool active; +} t_replication_slot; #define T_REPLICATION_SLOT_INITIALIZER { "", "", false } typedef struct s_connection_user { - char username[MAXLEN]; - bool is_superuser; -} t_connection_user; + char username[MAXLEN]; + bool is_superuser; +} t_connection_user; #define T_CONNECTION_USER_INITIALIZER { "", false } @@ -222,15 +230,15 @@ typedef struct s_connection_user /* represents an entry in bdr.bdr_nodes */ typedef struct s_bdr_node_info { - char node_sysid[MAXLEN]; - uint32 node_timeline; - uint32 node_dboid; - char node_status; - char node_name[MAXLEN]; - char node_local_dsn[MAXLEN]; - char node_init_from_dsn[MAXLEN]; - bool read_only; - uint32 node_seq_id; + char node_sysid[MAXLEN]; + uint32 node_timeline; + uint32 node_dboid; + char node_status; + char node_name[MAXLEN]; + char node_local_dsn[MAXLEN]; + char node_init_from_dsn[MAXLEN]; + bool read_only; + uint32 node_seq_id; } t_bdr_node_info; #define T_BDR_NODE_INFO_INITIALIZER { \ @@ -251,7 +259,7 @@ typedef struct BdrNodeInfoList { BdrNodeInfoListCell *head; BdrNodeInfoListCell *tail; - int node_count; + int node_count; } BdrNodeInfoList; #define T_BDR_NODE_INFO_LIST_INITIALIZER { \ @@ -260,7 +268,8 @@ typedef struct BdrNodeInfoList 0 \ } -typedef struct { +typedef struct +{ char current_timestamp[MAXLEN]; uint64 last_wal_receive_lsn; uint64 last_wal_replay_lsn; @@ -280,17 +289,17 @@ typedef struct { typedef struct { - char filepath[MAXPGPATH]; - char filename[MAXPGPATH]; - bool in_data_directory; + char filepath[MAXPGPATH]; + char filename[MAXPGPATH]; + bool in_data_directory; } t_configfile_info; #define T_CONFIGFILE_INFO_INITIALIZER { "", "", false } typedef struct { - int size; - int entries; + int size; + int entries; t_configfile_info **files; } t_configfile_list; @@ -298,9 +307,9 @@ typedef struct typedef struct { - uint64 system_identifier; - TimeLineID timeline; - XLogRecPtr xlogpos; + uint64 system_identifier; + TimeLineID timeline; + XLogRecPtr xlogpos; } t_system_identification; #define T_SYSTEM_IDENTIFICATION_INITIALIZER { \ @@ -310,7 +319,7 @@ typedef struct } /* global variables */ -extern int server_version_num; +extern int server_version_num; /* macros */ @@ -319,24 +328,25 @@ extern int server_version_num; /* utility functions */ -XLogRecPtr parse_lsn(const char *str); +XLogRecPtr parse_lsn(const char *str); -extern void wrap_ddl_query(PQExpBufferData *query_buf, int replication_type, const char *fmt, ...) +extern void +wrap_ddl_query(PQExpBufferData *query_buf, int replication_type, const char *fmt,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 4))); -bool atobool(const char *value); +bool atobool(const char *value); /* connection functions */ PGconn *establish_db_connection(const char *conninfo, - const bool exit_on_error); -PGconn *establish_db_connection_quiet(const char *conninfo); + const bool exit_on_error); +PGconn *establish_db_connection_quiet(const char *conninfo); PGconn *establish_db_connection_as_user(const char *conninfo, - const char *user, - const bool exit_on_error); + const char *user, + const bool exit_on_error); PGconn *establish_db_connection_by_params(t_conninfo_param_list *param_list, - const bool exit_on_error); + const bool exit_on_error); PGconn *establish_primary_db_connection(PGconn *conn, - const bool exit_on_error); + const bool exit_on_error); PGconn *get_primary_connection(PGconn *standby_conn, int *primary_id, char *primary_conninfo_out); PGconn *get_primary_connection_quiet(PGconn *standby_conn, int *primary_id, char *primary_conninfo_out); @@ -363,35 +373,35 @@ bool rollback_transaction(PGconn *conn); bool check_cluster_schema(PGconn *conn); /* GUC manipulation functions */ -bool set_config(PGconn *conn, const char *config_param, const char *config_value); +bool set_config(PGconn *conn, const char *config_param, const char *config_value); bool set_config_bool(PGconn *conn, const char *config_param, bool state); -int guc_set(PGconn *conn, const char *parameter, const char *op, - const char *value); -int guc_set_typed(PGconn *conn, const char *parameter, const char *op, +int guc_set(PGconn *conn, const char *parameter, const char *op, + const char *value); +int guc_set_typed(PGconn *conn, const char *parameter, const char *op, const char *value, const char *datatype); bool get_pg_setting(PGconn *conn, const char *setting, char *output); /* server information functions */ -bool get_cluster_size(PGconn *conn, char *size); -int get_server_version(PGconn *conn, char *server_version); +bool get_cluster_size(PGconn *conn, char *size); +int get_server_version(PGconn *conn, char *server_version); RecoveryType get_recovery_type(PGconn *conn); -int get_primary_node_id(PGconn *conn); -bool can_use_pg_rewind(PGconn *conn, const char *data_directory, PQExpBufferData *reason); -int get_ready_archive_files(PGconn *conn, const char *data_directory); -bool identify_system(PGconn *repl_conn, t_system_identification *identification); -bool repmgrd_set_local_node_id(PGconn *conn, int local_node_id); +int get_primary_node_id(PGconn *conn); +bool can_use_pg_rewind(PGconn *conn, const char *data_directory, PQExpBufferData *reason); +int get_ready_archive_files(PGconn *conn, const char *data_directory); +bool identify_system(PGconn *repl_conn, t_system_identification *identification); +bool repmgrd_set_local_node_id(PGconn *conn, int local_node_id); /* extension functions */ ExtensionStatus get_repmgr_extension_status(PGconn *conn); /* node management functions */ -void checkpoint(PGconn *conn); +void checkpoint(PGconn *conn); /* node record functions */ t_server_type parse_node_type(const char *type); -const char *get_node_type_string(t_server_type type); +const char *get_node_type_string(t_server_type type); RecordStatus get_node_record(PGconn *conn, int node_id, t_node_info *node_info); RecordStatus get_node_record_by_name(PGconn *conn, const char *node_name, t_node_info *node_info); @@ -445,53 +455,53 @@ int wait_connection_availability(PGconn *conn, long long timeout); bool is_server_available(const char *conninfo); /* monitoring functions */ -void add_monitoring_record( - PGconn *primary_conn, - PGconn *local_conn, - int primary_node_id, - int local_node_id, - char *monitor_standby_timestamp, - XLogRecPtr primary_last_wal_location, - XLogRecPtr last_wal_receive_lsn, - char *last_xact_replay_timestamp, - long long unsigned int replication_lag_bytes, - long long unsigned int apply_lag_bytes - ); +void +add_monitoring_record( + PGconn *primary_conn, + PGconn *local_conn, + int primary_node_id, + int local_node_id, + char *monitor_standby_timestamp, + XLogRecPtr primary_last_wal_location, + XLogRecPtr last_wal_receive_lsn, + char *last_xact_replay_timestamp, + long long unsigned int replication_lag_bytes, + long long unsigned int apply_lag_bytes +); /* node voting functions */ NodeVotingStatus get_voting_status(PGconn *conn); VoteRequestResult request_vote(PGconn *conn, t_node_info *this_node, t_node_info *other_node, int electoral_term); -int set_voting_status_initiated(PGconn *conn); -bool announce_candidature(PGconn *conn, t_node_info *this_node, t_node_info *other_node, int electoral_term); -void notify_follow_primary(PGconn *conn, int primary_node_id); -bool get_new_primary(PGconn *conn, int *primary_node_id); -void reset_voting_status(PGconn *conn); +int set_voting_status_initiated(PGconn *conn); +bool announce_candidature(PGconn *conn, t_node_info *this_node, t_node_info *other_node, int electoral_term); +void notify_follow_primary(PGconn *conn, int primary_node_id); +bool get_new_primary(PGconn *conn, int *primary_node_id); +void reset_voting_status(PGconn *conn); /* replication status functions */ -XLogRecPtr get_current_wal_lsn(PGconn *conn); -XLogRecPtr get_last_wal_receive_location(PGconn *conn); -bool get_replication_info(PGconn *conn, ReplInfo *replication_info); -int get_replication_lag_seconds(PGconn *conn); -void get_node_replication_stats(PGconn *conn, t_node_info *node_info); -bool is_downstream_node_attached(PGconn *conn, char *node_name); +XLogRecPtr get_current_wal_lsn(PGconn *conn); +XLogRecPtr get_last_wal_receive_location(PGconn *conn); +bool get_replication_info(PGconn *conn, ReplInfo *replication_info); +int get_replication_lag_seconds(PGconn *conn); +void get_node_replication_stats(PGconn *conn, t_node_info *node_info); +bool is_downstream_node_attached(PGconn *conn, char *node_name); /* BDR functions */ -void get_all_bdr_node_records(PGconn *conn, BdrNodeInfoList *node_list); +void get_all_bdr_node_records(PGconn *conn, BdrNodeInfoList *node_list); RecordStatus get_bdr_node_record_by_name(PGconn *conn, const char *node_name, t_bdr_node_info *node_info); -bool is_bdr_db(PGconn *conn, PQExpBufferData *output); -bool is_active_bdr_node(PGconn *conn, const char *node_name); -bool is_bdr_repmgr(PGconn *conn); -bool is_table_in_bdr_replication_set(PGconn *conn, const char *tablename, const char *set); -bool add_table_to_bdr_replication_set(PGconn *conn, const char *tablename, const char *set); -void add_extension_tables_to_bdr_replication_set(PGconn *conn); +bool is_bdr_db(PGconn *conn, PQExpBufferData *output); +bool is_active_bdr_node(PGconn *conn, const char *node_name); +bool is_bdr_repmgr(PGconn *conn); +bool is_table_in_bdr_replication_set(PGconn *conn, const char *tablename, const char *set); +bool add_table_to_bdr_replication_set(PGconn *conn, const char *tablename, const char *set); +void add_extension_tables_to_bdr_replication_set(PGconn *conn); -bool bdr_node_exists(PGconn *conn, const char *node_name); +bool bdr_node_exists(PGconn *conn, const char *node_name); ReplSlotStatus get_bdr_node_replication_slot_status(PGconn *conn, const char *node_name); -void get_bdr_other_node_name(PGconn *conn, int node_id, char *name_buf); +void get_bdr_other_node_name(PGconn *conn, int node_id, char *name_buf); -bool am_bdr_failover_handler(PGconn *conn, int node_id); -void unset_bdr_failover_handler(PGconn *conn); - -#endif /* _REPMGR_DBUTILS_H_ */ +bool am_bdr_failover_handler(PGconn *conn, int node_id); +void unset_bdr_failover_handler(PGconn *conn); +#endif /* _REPMGR_DBUTILS_H_ */ diff --git a/dirutil.c b/dirutil.c index 4bfd7795..4119c812 100644 --- a/dirutil.c +++ b/dirutil.c @@ -35,7 +35,7 @@ #include "strutil.h" #include "log.h" -static int unlink_dir_callback(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf); +static int unlink_dir_callback(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf); @@ -107,7 +107,7 @@ create_dir(char *path) return true; log_error(_("unable to create directory \"%s\": %s"), - path, strerror(errno)); + path, strerror(errno)); return false; } @@ -258,7 +258,7 @@ create_pg_dir(char *path, bool force) if (!create_dir(path)) { log_error(_("unable to create directory \"%s\"..."), - path); + path); return false; } break; @@ -270,7 +270,7 @@ create_pg_dir(char *path, bool force) if (!set_dir_permissions(path)) { log_error(_("unable to change permissions of directory \"%s\":\n %s"), - path, strerror(errno)); + path, strerror(errno)); return false; } break; @@ -296,16 +296,16 @@ create_pg_dir(char *path, bool force) else if (pg_dir && !force) { log_hint(_("This looks like a PostgreSQL directory.\n" - "If you are sure you want to clone here, " - "please check there is no PostgreSQL server " - "running and use the -F/--force option")); + "If you are sure you want to clone here, " + "please check there is no PostgreSQL server " + "running and use the -F/--force option")); return false; } return false; default: log_error(_("could not access directory \"%s\": %s"), - path, strerror(errno)); + path, strerror(errno)); return false; } return true; @@ -314,11 +314,10 @@ create_pg_dir(char *path, bool force) static int unlink_dir_callback(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { - int rv = remove(fpath); + int rv = remove(fpath); - if (rv) - perror(fpath); + if (rv) + perror(fpath); - return rv; + return rv; } - diff --git a/dirutil.h b/dirutil.h index d8127b89..0743752b 100644 --- a/dirutil.h +++ b/dirutil.h @@ -19,12 +19,12 @@ #ifndef _DIRUTIL_H_ #define _DIRUTIL_H_ -extern int mkdir_p(char *path, mode_t omode); -extern bool set_dir_permissions(char *path); +extern int mkdir_p(char *path, mode_t omode); +extern bool set_dir_permissions(char *path); -extern int check_dir(char *path); -extern bool create_dir(char *path); -extern bool is_pg_dir(char *path); -extern bool create_pg_dir(char *path, bool force); +extern int check_dir(char *path); +extern bool create_dir(char *path); +extern bool is_pg_dir(char *path); +extern bool create_pg_dir(char *path, bool force); #endif diff --git a/errcode.h b/errcode.h index 3d37a9b8..e29e8c21 100644 --- a/errcode.h +++ b/errcode.h @@ -44,5 +44,4 @@ #define ERR_REGISTRATION_SYNC 20 #define ERR_OUT_OF_MEMORY 21 -#endif /* _ERRCODE_H_ */ - +#endif /* _ERRCODE_H_ */ diff --git a/log.c b/log.c index 7288280c..99676a2f 100644 --- a/log.c +++ b/log.c @@ -37,7 +37,8 @@ /* #define REPMGR_DEBUG */ static int detect_log_facility(const char *facility); -static void _stderr_log_with_level(const char *level_name, int level, const char *fmt, va_list ap) +static void +_stderr_log_with_level(const char *level_name, int level, const char *fmt, va_list ap) __attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 0))); int log_type = REPMGR_STDERR; @@ -45,6 +46,7 @@ int log_level = LOG_NOTICE; int last_log_level = LOG_INFO; int verbose_logging = false; int terse_logging = false; + /* * Global variable to be set by the main application to ensure any log output * emitted before logger_init is called, is output in the correct format @@ -52,7 +54,7 @@ int terse_logging = false; int logger_output_mode = OM_DAEMON; extern void -stderr_log_with_level(const char *level_name, int level, const char *fmt, ...) +stderr_log_with_level(const char *level_name, int level, const char *fmt,...) { va_list arglist; @@ -67,8 +69,8 @@ _stderr_log_with_level(const char *level_name, int level, const char *fmt, va_li char buf[100]; /* - * Store the requested level so that if there's a subsequent - * log_hint() or log_detail(), we can suppress that if appropriate. + * Store the requested level so that if there's a subsequent log_hint() or + * log_detail(), we can suppress that if appropriate. */ last_log_level = level; @@ -80,6 +82,7 @@ _stderr_log_with_level(const char *level_name, int level, const char *fmt, va_li { time_t t; struct tm *tm; + time(&t); tm = localtime(&t); strftime(buf, 100, "[%Y-%m-%d %H:%M:%S]", tm); @@ -97,7 +100,7 @@ _stderr_log_with_level(const char *level_name, int level, const char *fmt, va_li } void -log_hint(const char *fmt, ...) +log_hint(const char *fmt,...) { va_list ap; @@ -111,7 +114,7 @@ log_hint(const char *fmt, ...) void -log_detail(const char *fmt, ...) +log_detail(const char *fmt,...) { va_list ap; @@ -125,7 +128,7 @@ log_detail(const char *fmt, ...) void -log_verbose(int level, const char *fmt, ...) +log_verbose(int level, const char *fmt,...) { va_list ap; @@ -133,7 +136,7 @@ log_verbose(int level, const char *fmt, ...) if (verbose_logging == true) { - switch(level) + switch (level) { case LOG_EMERG: _stderr_log_with_level("EMERG", level, fmt, ap); @@ -202,8 +205,8 @@ logger_init(t_configuration_options *opts, const char *ident) } /* - * STDERR only logging requested - finish here without setting up any further - * logging facility. + * STDERR only logging requested - finish here without setting up any + * further logging facility. */ if (logger_output_mode == OM_COMMAND_LINE) return true; @@ -251,9 +254,10 @@ logger_init(t_configuration_options *opts, const char *ident) { FILE *fd; - /* Check if we can write to the specified file before redirecting - * stderr - if freopen() fails, stderr output will vanish into - * the ether and the user won't know what's going on. + /* + * Check if we can write to the specified file before redirecting + * stderr - if freopen() fails, stderr output will vanish into the + * ether and the user won't know what's going on. */ fd = fopen(opts->log_file, "a"); @@ -270,9 +274,9 @@ logger_init(t_configuration_options *opts, const char *ident) fd = freopen(opts->log_file, "a", stderr); /* - * It's possible freopen() may still fail due to e.g. a race condition; - * as it's not feasible to restore stderr after a failed freopen(), - * we'll write to stdout as a last resort. + * It's possible freopen() may still fail due to e.g. a race + * condition; as it's not feasible to restore stderr after a failed + * freopen(), we'll write to stdout as a last resort. */ if (fd == NULL) { @@ -318,7 +322,8 @@ logger_set_verbose(void) * options and hints. */ -void logger_set_terse(void) +void +logger_set_terse(void) { terse_logging = true; } diff --git a/log.h b/log.h index c157f7d5..b10a29e7 100644 --- a/log.h +++ b/log.h @@ -122,18 +122,21 @@ int detect_log_level(const char *level); /* Logger initialisation and shutdown */ -bool logger_init(t_configuration_options * opts, const char *ident); +bool logger_init(t_configuration_options *opts, const char *ident); bool logger_shutdown(void); void logger_set_verbose(void); void logger_set_terse(void); -void log_detail(const char *fmt, ...) +void +log_detail(const char *fmt,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2))); -void log_hint(const char *fmt, ...) +void +log_hint(const char *fmt,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2))); -void log_verbose(int level, const char *fmt, ...) +void +log_verbose(int level, const char *fmt,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3))); extern int log_type; @@ -142,4 +145,4 @@ extern int verbose_logging; extern int terse_logging; extern int logger_output_mode; -#endif /* _REPMGR_LOG_H_ */ +#endif /* _REPMGR_LOG_H_ */ diff --git a/repmgr-action-bdr.c b/repmgr-action-bdr.c index 14086269..78e4fa4e 100644 --- a/repmgr-action-bdr.c +++ b/repmgr-action-bdr.c @@ -34,14 +34,14 @@ void do_bdr_register(void) { - PGconn *conn = NULL; + PGconn *conn = NULL; BdrNodeInfoList bdr_nodes = T_BDR_NODE_INFO_LIST_INITIALIZER; - ExtensionStatus extension_status = REPMGR_UNKNOWN; - t_node_info node_info = T_NODE_INFO_INITIALIZER; - RecordStatus record_status = RECORD_NOT_FOUND; + ExtensionStatus extension_status = REPMGR_UNKNOWN; + t_node_info node_info = T_NODE_INFO_INITIALIZER; + RecordStatus record_status = RECORD_NOT_FOUND; PQExpBufferData event_details; - bool success = true; - char dbname[MAXLEN]; + bool success = true; + char dbname[MAXLEN]; /* sanity-check configuration for BDR-compatability */ if (config_file_options.replication_type != REPLICATION_TYPE_BDR) @@ -124,7 +124,7 @@ do_bdr_register(void) /* check for a matching BDR node */ { - bool node_exists = bdr_node_exists(conn, config_file_options.node_name); + bool node_exists = bdr_node_exists(conn, config_file_options.node_name); if (node_exists == false) { @@ -136,15 +136,15 @@ do_bdr_register(void) } /* - * before adding the extension tables to the replication set, - * if any other BDR nodes exist, populate repmgr.nodes with a copy - * of existing entries + * before adding the extension tables to the replication set, if any other + * BDR nodes exist, populate repmgr.nodes with a copy of existing entries * * currently we won't copy the contents of any other tables * */ { NodeInfoList local_node_records = T_NODE_INFO_LIST_INITIALIZER; + get_all_node_records(conn, &local_node_records); if (local_node_records.node_count == 0) @@ -163,7 +163,7 @@ do_bdr_register(void) for (bdr_cell = bdr_nodes.head; bdr_cell; bdr_cell = bdr_cell->next) { - PGconn *bdr_node_conn = NULL; + PGconn *bdr_node_conn = NULL; NodeInfoList existing_nodes = T_NODE_INFO_LIST_INITIALIZER; NodeInfoListCell *cell = NULL; ExtensionStatus other_node_extension_status = REPMGR_UNKNOWN; @@ -235,10 +235,11 @@ do_bdr_register(void) if (record_status == RECORD_FOUND) { - bool node_updated = false; + bool node_updated = false; + /* - * At this point we will have established there are no non-BDR records, - * so no need to verify the node type + * At this point we will have established there are no non-BDR + * records, so no need to verify the node type */ if (!runtime_options.force) { @@ -250,8 +251,8 @@ do_bdr_register(void) } /* - * don't permit changing the node name - this must match the - * BDR node name set when the node was registered. + * don't permit changing the node name - this must match the BDR node + * name set when the node was registered. */ if (strncmp(node_info.node_name, config_file_options.node_name, MAXLEN) != 0) @@ -281,7 +282,7 @@ do_bdr_register(void) else { /* create new node record */ - bool node_created = create_node_record(conn, "bdr register", &node_info); + bool node_created = create_node_record(conn, "bdr register", &node_info); if (node_created == true) { @@ -306,12 +307,12 @@ do_bdr_register(void) commit_transaction(conn); /* Log the event */ create_event_notification( - conn, - &config_file_options, - config_file_options.node_id, - "bdr_register", - true, - event_details.data); + conn, + &config_file_options, + config_file_options.node_id, + "bdr_register", + true, + event_details.data); termPQExpBuffer(&event_details); @@ -327,14 +328,14 @@ do_bdr_register(void) void do_bdr_unregister(void) { - PGconn *conn = NULL; - ExtensionStatus extension_status = REPMGR_UNKNOWN; - int target_node_id = UNKNOWN_NODE_ID; - t_node_info node_info = T_NODE_INFO_INITIALIZER; - RecordStatus record_status = RECORD_NOT_FOUND; - bool node_record_deleted = false; + PGconn *conn = NULL; + ExtensionStatus extension_status = REPMGR_UNKNOWN; + int target_node_id = UNKNOWN_NODE_ID; + t_node_info node_info = T_NODE_INFO_INITIALIZER; + RecordStatus record_status = RECORD_NOT_FOUND; + bool node_record_deleted = false; PQExpBufferData event_details; - char dbname[MAXLEN]; + char dbname[MAXLEN]; /* sanity-check configuration for BDR-compatability */ @@ -411,12 +412,12 @@ do_bdr_unregister(void) /* Log the event */ create_event_notification( - conn, - &config_file_options, - config_file_options.node_id, - "bdr_unregister", - true, - event_details.data); + conn, + &config_file_options, + config_file_options.node_id, + "bdr_unregister", + true, + event_details.data); PQfinish(conn); diff --git a/repmgr-action-bdr.h b/repmgr-action-bdr.h index 601cdccf..860bfa78 100644 --- a/repmgr-action-bdr.h +++ b/repmgr-action-bdr.h @@ -25,4 +25,4 @@ extern void do_bdr_unregister(void); extern void do_bdr_help(void); -#endif /* _REPMGR_ACTION_BDR_H_ */ +#endif /* _REPMGR_ACTION_BDR_H_ */ diff --git a/repmgr-action-cluster.c b/repmgr-action-cluster.c index c209573d..ee17b9c0 100644 --- a/repmgr-action-cluster.c +++ b/repmgr-action-cluster.c @@ -27,7 +27,8 @@ #define SHOW_HEADER_COUNT 7 -typedef enum { +typedef enum +{ SHOW_ID = 0, SHOW_NAME, SHOW_ROLE, @@ -35,25 +36,27 @@ typedef enum { SHOW_UPSTREAM_NAME, SHOW_LOCATION, SHOW_CONNINFO -} ShowHeader; +} ShowHeader; #define EVENT_HEADER_COUNT 6 -typedef enum { +typedef enum +{ EV_NODE_ID = 0, EV_NODE_NAME, EV_EVENT, EV_SUCCESS, EV_TIMESTAMP, EV_DETAILS -} EventHeader; +} EventHeader; -struct ColHeader { - char title[MAXLEN]; - int max_length; - int cur_length; +struct ColHeader +{ + char title[MAXLEN]; + int max_length; + int cur_length; }; struct ColHeader headers_show[SHOW_HEADER_COUNT]; @@ -61,8 +64,8 @@ struct ColHeader headers_event[EVENT_HEADER_COUNT]; -static int build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length); -static int build_cluster_crosscheck(t_node_status_cube ***cube_dest, int *name_length); +static int build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length); +static int build_cluster_crosscheck(t_node_status_cube ***cube_dest, int *name_length); static void cube_set_node_status(t_node_status_cube **cube, int n, int node_id, int matrix_node_id, int connection_node_id, int connection_status); /* @@ -78,7 +81,7 @@ do_cluster_show(void) NodeInfoList nodes = T_NODE_INFO_LIST_INITIALIZER; NodeInfoListCell *cell = NULL; int i = 0; - ItemList warnings = { NULL, NULL }; + ItemList warnings = {NULL, NULL}; /* Connect to local database to obtain cluster connection data */ log_verbose(LOG_INFO, _("connecting to database\n")); @@ -106,8 +109,8 @@ do_cluster_show(void) strncpy(headers_show[SHOW_CONNINFO].title, _("Connection string"), MAXLEN); /* - * NOTE: if repmgr is ever localized into non-ASCII locales, - * use pg_wcssize() or similar to establish printed column length + * NOTE: if repmgr is ever localized into non-ASCII locales, use + * pg_wcssize() or similar to establish printed column length */ for (i = 0; i < SHOW_HEADER_COUNT; i++) @@ -136,171 +139,172 @@ do_cluster_show(void) /* * TODO: count nodes marked as "? unreachable" and add a hint about - * the other cluster commands for better determining whether unreachable. + * the other cluster commands for better determining whether + * unreachable. */ switch (cell->node_info->type) { case PRIMARY: - { - /* node is reachable */ - if (cell->node_info->node_status == NODE_STATUS_UP) { - if (cell->node_info->active == true) + /* node is reachable */ + if (cell->node_info->node_status == NODE_STATUS_UP) { - switch (cell->node_info->recovery_type) + if (cell->node_info->active == true) { - case RECTYPE_PRIMARY: - appendPQExpBuffer(&details, "* running"); - break; - case RECTYPE_STANDBY: + switch (cell->node_info->recovery_type) + { + case RECTYPE_PRIMARY: + appendPQExpBuffer(&details, "* running"); + break; + case RECTYPE_STANDBY: + appendPQExpBuffer(&details, "! running as standby"); + item_list_append_format( + &warnings, + "node \"%s\" (ID: %i) is registered as primary but running as standby", + cell->node_info->node_name, cell->node_info->node_id); + break; + case RECTYPE_UNKNOWN: + appendPQExpBuffer(&details, "! unknown"); + item_list_append_format( + &warnings, + "node \"%s\" (ID: %i) has unknown replication status", + cell->node_info->node_name, cell->node_info->node_id); + break; + } + } + else + { + if (cell->node_info->recovery_type == RECTYPE_PRIMARY) + { + appendPQExpBuffer(&details, "! running"); + item_list_append_format( + &warnings, + "node \"%s\" (ID: %i) is running but the repmgr node record is inactive", + cell->node_info->node_name, cell->node_info->node_id); + } + else + { appendPQExpBuffer(&details, "! running as standby"); item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) is registered as primary but running as standby", - cell->node_info->node_name, cell->node_info->node_id); - break; - case RECTYPE_UNKNOWN: - appendPQExpBuffer(&details, "! unknown"); - item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) has unknown replication status", - cell->node_info->node_name, cell->node_info->node_id); - break; + &warnings, + "node \"%s\" (ID: %i) is registered as an inactive primary but running as standby", + cell->node_info->node_name, cell->node_info->node_id); + } } } + /* node is unreachable */ else { - if (cell->node_info->recovery_type == RECTYPE_PRIMARY) + /* node is unreachable but marked active */ + if (cell->node_info->active == true) { - appendPQExpBuffer(&details, "! running"); + appendPQExpBuffer(&details, "? unreachable"); item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) is running but the repmgr node record is inactive", - cell->node_info->node_name, cell->node_info->node_id); + &warnings, + "node \"%s\" (ID: %i) is registered as an active primary but is unreachable", + cell->node_info->node_name, cell->node_info->node_id); } + /* node is unreachable and marked as inactive */ else { - appendPQExpBuffer(&details, "! running as standby"); - item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) is registered as an inactive primary but running as standby", - cell->node_info->node_name, cell->node_info->node_id); + appendPQExpBuffer(&details, "- failed"); } } } - /* node is unreachable */ - else - { - /* node is unreachable but marked active*/ - if (cell->node_info->active == true) - { - appendPQExpBuffer(&details, "? unreachable"); - item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) is registered as an active primary but is unreachable", - cell->node_info->node_name, cell->node_info->node_id); - } - /* node is unreachable and marked as inactive */ - else - { - appendPQExpBuffer(&details, "- failed"); - } - } - } - break; + break; case STANDBY: - { - /* node is reachable */ - if (cell->node_info->node_status == NODE_STATUS_UP) { - if (cell->node_info->active == true) + /* node is reachable */ + if (cell->node_info->node_status == NODE_STATUS_UP) { - switch (cell->node_info->recovery_type) + if (cell->node_info->active == true) { - case RECTYPE_STANDBY: - appendPQExpBuffer(&details, " running"); - break; - case RECTYPE_PRIMARY: - appendPQExpBuffer(&details, "! running as primary"); - item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) is registered as standby but running as primary", - cell->node_info->node_name, cell->node_info->node_id); - break; - case RECTYPE_UNKNOWN: - appendPQExpBuffer(&details, "! unknown"); - item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) has unknown replication status", - cell->node_info->node_name, cell->node_info->node_id); - break; - } - } - else - { - if (cell->node_info->recovery_type == RECTYPE_STANDBY) - { - appendPQExpBuffer(&details, "! running"); - item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) is running but the repmgr node record is inactive", - cell->node_info->node_name, cell->node_info->node_id); + switch (cell->node_info->recovery_type) + { + case RECTYPE_STANDBY: + appendPQExpBuffer(&details, " running"); + break; + case RECTYPE_PRIMARY: + appendPQExpBuffer(&details, "! running as primary"); + item_list_append_format( + &warnings, + "node \"%s\" (ID: %i) is registered as standby but running as primary", + cell->node_info->node_name, cell->node_info->node_id); + break; + case RECTYPE_UNKNOWN: + appendPQExpBuffer(&details, "! unknown"); + item_list_append_format( + &warnings, + "node \"%s\" (ID: %i) has unknown replication status", + cell->node_info->node_name, cell->node_info->node_id); + break; + } } else { - appendPQExpBuffer(&details, "! running as primary"); + if (cell->node_info->recovery_type == RECTYPE_STANDBY) + { + appendPQExpBuffer(&details, "! running"); + item_list_append_format( + &warnings, + "node \"%s\" (ID: %i) is running but the repmgr node record is inactive", + cell->node_info->node_name, cell->node_info->node_id); + } + else + { + appendPQExpBuffer(&details, "! running as primary"); + item_list_append_format( + &warnings, + "node \"%s\" (ID: %i) is running as primary but the repmgr node record is inactive", + cell->node_info->node_name, cell->node_info->node_id); + } + } + } + /* node is unreachable */ + else + { + /* node is unreachable but marked active */ + if (cell->node_info->active == true) + { + appendPQExpBuffer(&details, "? unreachable"); item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) is running as primary but the repmgr node record is inactive", - cell->node_info->node_name, cell->node_info->node_id); + &warnings, + "node \"%s\" (ID: %i) is registered as an active standby but is unreachable", + cell->node_info->node_name, cell->node_info->node_id); + } + else + { + appendPQExpBuffer(&details, "- failed"); } } } - /* node is unreachable */ - else - { - /* node is unreachable but marked active*/ - if (cell->node_info->active == true) - { - appendPQExpBuffer(&details, "? unreachable"); - item_list_append_format( - &warnings, - "node \"%s\" (ID: %i) is registered as an active standby but is unreachable", - cell->node_info->node_name, cell->node_info->node_id); - } - else - { - appendPQExpBuffer(&details, "- failed"); - } - } - } - break; + break; case BDR: - { - /* node is reachable */ - if (cell->node_info->node_status == NODE_STATUS_UP) { - if (cell->node_info->active == true) - appendPQExpBuffer(&details, "* running"); + /* node is reachable */ + if (cell->node_info->node_status == NODE_STATUS_UP) + { + if (cell->node_info->active == true) + appendPQExpBuffer(&details, "* running"); + else + appendPQExpBuffer(&details, "! running"); + } + /* node is unreachable */ else - appendPQExpBuffer(&details, "! running"); + { + if (cell->node_info->active == true) + appendPQExpBuffer(&details, "? unreachable"); + else + appendPQExpBuffer(&details, "- failed"); + } } - /* node is unreachable */ - else - { - if (cell->node_info->active == true) - appendPQExpBuffer(&details, "? unreachable"); - else - appendPQExpBuffer(&details, "- failed"); - } - } - break; + break; case UNKNOWN: - { - /* this should never happen */ - appendPQExpBuffer(&details, "? unknown node type"); - } - break; + { + /* this should never happen */ + appendPQExpBuffer(&details, "? unknown node type"); + } + break; } strncpy(cell->node_info->details, details.data, MAXLEN); @@ -344,7 +348,8 @@ do_cluster_show(void) for (i = 0; i < SHOW_HEADER_COUNT; i++) { - int j; + int j; + for (j = 0; j < headers_show[i].max_length; j++) printf("-"); @@ -361,12 +366,12 @@ do_cluster_show(void) { if (runtime_options.output_mode == OM_CSV) { - int connection_status = (cell->node_info->node_status == NODE_STATUS_UP) ? 0 : -1; - int recovery_type = RECTYPE_UNKNOWN; + int connection_status = (cell->node_info->node_status == NODE_STATUS_UP) ? 0 : -1; + int recovery_type = RECTYPE_UNKNOWN; /* - * here we explicitly convert the RecoveryType to integer values to - * avoid implicit dependency on the values in the enum + * here we explicitly convert the RecoveryType to integer values + * to avoid implicit dependency on the values in the enum */ switch (cell->node_info->recovery_type) { @@ -388,12 +393,12 @@ do_cluster_show(void) } else { - printf( " %-*i ", headers_show[SHOW_ID].max_length, cell->node_info->node_id); - printf("| %-*s ", headers_show[SHOW_NAME].max_length, cell->node_info->node_name); - printf("| %-*s ", headers_show[SHOW_ROLE].max_length, get_node_type_string(cell->node_info->type)); - printf("| %-*s ", headers_show[SHOW_STATUS].max_length, cell->node_info->details); - printf("| %-*s ", headers_show[SHOW_UPSTREAM_NAME].max_length , cell->node_info->upstream_node_name); - printf("| %-*s ", headers_show[SHOW_LOCATION].max_length , cell->node_info->location); + printf(" %-*i ", headers_show[SHOW_ID].max_length, cell->node_info->node_id); + printf("| %-*s ", headers_show[SHOW_NAME].max_length, cell->node_info->node_name); + printf("| %-*s ", headers_show[SHOW_ROLE].max_length, get_node_type_string(cell->node_info->type)); + printf("| %-*s ", headers_show[SHOW_STATUS].max_length, cell->node_info->details); + printf("| %-*s ", headers_show[SHOW_UPSTREAM_NAME].max_length, cell->node_info->upstream_node_name); + printf("| %-*s ", headers_show[SHOW_LOCATION].max_length, cell->node_info->location); printf("| %-*s\n", headers_show[SHOW_CONNINFO].max_length, cell->node_info->conninfo); } } @@ -429,11 +434,11 @@ do_cluster_show(void) void do_cluster_event(void) { - PGconn *conn = NULL; - PQExpBufferData query; - PQExpBufferData where_clause; - PGresult *res; - int i = 0; + PGconn *conn = NULL; + PQExpBufferData query; + PQExpBufferData where_clause; + PGresult *res; + int i = 0; conn = establish_db_connection(config_file_options.conninfo, true); @@ -442,12 +447,12 @@ do_cluster_event(void) /* LEFT JOIN used here as a node record may have been removed */ appendPQExpBuffer( - &query, - " SELECT e.node_id, n.node_name, e.event, e.successful, \n" - " TO_CHAR(e.event_timestamp, 'YYYY-MM-DD HH24:MI:SS') AS timestamp, \n" - " e.details \n" - " FROM repmgr.events e \n" - "LEFT JOIN repmgr.nodes n ON e.node_id = n.node_id "); + &query, + " SELECT e.node_id, n.node_name, e.event, e.successful, \n" + " TO_CHAR(e.event_timestamp, 'YYYY-MM-DD HH24:MI:SS') AS timestamp, \n" + " e.details \n" + " FROM repmgr.events e \n" + "LEFT JOIN repmgr.nodes n ON e.node_id = n.node_id "); if (runtime_options.node_id != UNKNOWN_NODE_ID) { @@ -457,7 +462,7 @@ do_cluster_event(void) } else if (runtime_options.node_name[0] != '\0') { - char *escaped = escape_string(conn, runtime_options.node_name); + char *escaped = escape_string(conn, runtime_options.node_name); if (escaped == NULL) { @@ -474,7 +479,7 @@ do_cluster_event(void) if (runtime_options.event[0] != '\0') { - char *escaped = escape_string(conn, runtime_options.event); + char *escaped = escape_string(conn, runtime_options.event); if (escaped == NULL) { @@ -516,7 +521,8 @@ do_cluster_event(void) exit(ERR_DB_QUERY); } - if (PQntuples(res) == 0) { + if (PQntuples(res) == 0) + { /* print this message directly, rather than as a log line */ printf(_("no matching events found\n")); PQclear(res); @@ -536,14 +542,14 @@ do_cluster_event(void) headers_event[i].max_length = strlen(headers_event[i].title); } - for(i = 0; i < PQntuples(res); i++) + for (i = 0; i < PQntuples(res); i++) { - int j; + int j; for (j = 0; j < EVENT_HEADER_COUNT; j++) { headers_event[j].cur_length = strlen(PQgetvalue(res, i, j)); - if(headers_event[j].cur_length > headers_event[j].max_length) + if (headers_event[j].cur_length > headers_event[j].max_length) { headers_event[j].max_length = headers_event[j].cur_length; } @@ -566,7 +572,8 @@ do_cluster_event(void) printf("-"); for (i = 0; i < EVENT_HEADER_COUNT; i++) { - int j; + int j; + for (j = 0; j < headers_event[i].max_length; j++) printf("-"); @@ -578,9 +585,9 @@ do_cluster_event(void) printf("\n"); - for(i = 0; i < PQntuples(res); i++) + for (i = 0; i < PQntuples(res); i++) { - int j; + int j; printf(" "); for (j = 0; j < EVENT_HEADER_COUNT; j++) @@ -590,7 +597,7 @@ do_cluster_event(void) PQgetvalue(res, i, j)); if (j < (EVENT_HEADER_COUNT - 1)) - printf(" | "); + printf(" | "); } printf("\n"); @@ -607,7 +614,8 @@ do_cluster_event(void) void do_cluster_crosscheck(void) { - int i = 0, n = 0; + int i = 0, + n = 0; char c; const char *node_header = "Name"; int name_length = strlen(node_header); @@ -630,7 +638,7 @@ do_cluster_crosscheck(void) for (i = 0; i < n; i++) { - int column_node_ix; + int column_node_ix; printf("%*s | %2d ", name_length, cube[i]->node_name, @@ -638,26 +646,27 @@ do_cluster_crosscheck(void) for (column_node_ix = 0; column_node_ix < n; column_node_ix++) { - int max_node_status = -2; - int node_ix = 0; + int max_node_status = -2; + int node_ix = 0; /* - * The value of entry (i,j) is equal to the - * maximum value of all the (i,j,k). Indeed: + * The value of entry (i,j) is equal to the maximum value of all + * the (i,j,k). Indeed: * - * - if one of the (i,j,k) is 0 (node up), then 0 - * (the node is up); + * - if one of the (i,j,k) is 0 (node up), then 0 (the node is + * up); * - * - if the (i,j,k) are either -1 (down) or -2 - * (unknown), then -1 (the node is down); + * - if the (i,j,k) are either -1 (down) or -2 (unknown), then -1 + * (the node is down); * - * - if all the (i,j,k) are -2 (unknown), then -2 - * (the node is in an unknown state). + * - if all the (i,j,k) are -2 (unknown), then -2 (the node is in + * an unknown state). */ - for(node_ix = 0; node_ix < n; node_ix ++) + for (node_ix = 0; node_ix < n; node_ix++) { - int node_status = cube[node_ix]->matrix_list_rec[i]->node_status_list[column_node_ix]->node_status; + int node_status = cube[node_ix]->matrix_list_rec[i]->node_status_list[column_node_ix]->node_status; + if (node_status > max_node_status) max_node_status = node_status; } @@ -685,7 +694,9 @@ do_cluster_crosscheck(void) /* clean up allocated cube array */ { - int h, j; + int h, + j; + for (h = 0; h < n; h++) { for (i = 0; i < n; i++) @@ -710,7 +721,9 @@ do_cluster_crosscheck(void) void do_cluster_matrix() { - int i = 0, j = 0, n = 0; + int i = 0, + j = 0, + n = 0; const char *node_header = "Name"; int name_length = strlen(node_header); @@ -730,7 +743,7 @@ do_cluster_matrix() } else { - char c; + char c; printf("%*s | Id ", name_length, node_header); for (i = 0; i < n; i++) @@ -753,17 +766,17 @@ do_cluster_matrix() { switch (matrix_rec_list[i]->node_status_list[j]->node_status) { - case -2: - c = '?'; - break; - case -1: - c = 'x'; - break; - case 0: - c = '*'; - break; - default: - exit(ERR_INTERNAL); + case -2: + c = '?'; + break; + case -1: + c = 'x'; + break; + case 0: + c = '*'; + break; + default: + exit(ERR_INTERNAL); } printf("| %c ", c); @@ -789,7 +802,8 @@ do_cluster_matrix() static void matrix_set_node_status(t_node_matrix_rec **matrix_rec_list, int n, int node_id, int connection_node_id, int connection_status) { - int i, j; + int i, + j; for (i = 0; i < n; i++) { @@ -812,10 +826,11 @@ matrix_set_node_status(t_node_matrix_rec **matrix_rec_list, int n, int node_id, static int build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) { - PGconn *conn = NULL; - int i = 0, j = 0; - int local_node_id = UNKNOWN_NODE_ID; - int node_count = 0; + PGconn *conn = NULL; + int i = 0, + j = 0; + int local_node_id = UNKNOWN_NODE_ID; + int node_count = 0; NodeInfoList nodes = T_NODE_INFO_LIST_INITIALIZER; NodeInfoListCell *cell = NULL; @@ -852,9 +867,7 @@ build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) /* * Allocate an empty matrix record list * - * -2 == NULL ? - * -1 == Error x - * 0 == OK * + * -2 == NULL ? -1 == Error x 0 == OK * */ matrix_rec_list = (t_node_matrix_rec **) pg_malloc0(sizeof(t_node_matrix_rec) * nodes.node_count); @@ -864,7 +877,7 @@ build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) /* Initialise matrix structure for each node */ for (cell = nodes.head; cell; cell = cell->next) { - int name_length_cur; + int name_length_cur; NodeInfoListCell *cell_j; matrix_rec_list[i] = (t_node_matrix_rec *) pg_malloc0(sizeof(t_node_matrix_rec)); @@ -875,7 +888,7 @@ build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) /* * Find the maximum length of a node name */ - name_length_cur = strlen(matrix_rec_list[i]->node_name); + name_length_cur = strlen(matrix_rec_list[i]->node_name); if (name_length_cur > *name_length) *name_length = name_length_cur; @@ -887,7 +900,7 @@ build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) { matrix_rec_list[i]->node_status_list[j] = (t_node_status_rec *) pg_malloc0(sizeof(t_node_status_rec)); matrix_rec_list[i]->node_status_list[j]->node_id = cell_j->node_info->node_id; - matrix_rec_list[i]->node_status_list[j]->node_status = -2; /* default unknown */ + matrix_rec_list[i]->node_status_list[j]->node_status = -2; /* default unknown */ j++; } @@ -900,12 +913,14 @@ build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) for (cell = nodes.head; cell; cell = cell->next) { - int connection_status = 0; + int connection_status = 0; t_conninfo_param_list remote_conninfo = T_CONNINFO_PARAM_LIST_INITIALIZER; - char *host = NULL, *p = NULL; - int connection_node_id = cell->node_info->node_id; - int x, y; - PGconn *node_conn = NULL; + char *host = NULL, + *p = NULL; + int connection_node_id = cell->node_info->node_id; + int x, + y; + PGconn *node_conn = NULL; initialize_conninfo_params(&remote_conninfo, false); parse_conninfo_string(cell->node_info->conninfo, @@ -948,9 +963,9 @@ build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) initPQExpBuffer(&command); /* - * We'll pass cluster name and database connection string to the remote - * repmgr - those are the only values it needs to work, and saves us - * making assumptions about the location of repmgr.conf + * We'll pass cluster name and database connection string to the + * remote repmgr - those are the only values it needs to work, and + * saves us making assumptions about the location of repmgr.conf */ appendPQExpBuffer(&command, "\"%s -d '%s' ", @@ -975,11 +990,11 @@ build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) initPQExpBuffer(&command_output); - (void)remote_command( - host, - runtime_options.remote_user, - command.data, - &command_output); + (void) remote_command( + host, + runtime_options.remote_user, + command.data, + &command_output); p = command_output.data; @@ -998,7 +1013,7 @@ build_cluster_matrix(t_node_matrix_rec ***matrix_rec_dest, int *name_length) nodes.node_count, connection_node_id, x, - (y == -1) ? -1 : 0 ); + (y == -1) ? -1 : 0); while (*p && (*p != '\n')) p++; @@ -1026,13 +1041,15 @@ static int build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) { PGconn *conn = NULL; - int h, i, j; + int h, + i, + j; NodeInfoList nodes = T_NODE_INFO_LIST_INITIALIZER; NodeInfoListCell *cell = NULL; t_node_status_cube **cube; - int node_count = 0; + int node_count = 0; /* We need to connect to get the list of nodes */ log_info(_("connecting to database\n")); @@ -1056,9 +1073,7 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) /* * Allocate an empty cube matrix structure * - * -2 == NULL - * -1 == Error - * 0 == OK + * -2 == NULL -1 == Error 0 == OK */ cube = (t_node_status_cube **) pg_malloc(sizeof(t_node_status_cube *) * nodes.node_count); @@ -1067,7 +1082,7 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) for (cell = nodes.head; cell; cell = cell->next) { - int name_length_cur = 0; + int name_length_cur = 0; NodeInfoListCell *cell_i = NULL; cube[h] = (t_node_status_cube *) pg_malloc(sizeof(t_node_status_cube)); @@ -1077,7 +1092,7 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) /* * Find the maximum length of a node name */ - name_length_cur = strlen(cube[h]->node_name); + name_length_cur = strlen(cube[h]->node_name); if (name_length_cur > *name_length) *name_length = name_length_cur; @@ -1102,7 +1117,7 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) { cube[h]->matrix_list_rec[i]->node_status_list[j] = (t_node_status_rec *) pg_malloc0(sizeof(t_node_status_rec)); cube[h]->matrix_list_rec[i]->node_status_list[j]->node_id = cell_j->node_info->node_id; - cube[h]->matrix_list_rec[i]->node_status_list[j]->node_status = -2; /* default unknown */ + cube[h]->matrix_list_rec[i]->node_status_list[j]->node_status = -2; /* default unknown */ j++; } @@ -1121,7 +1136,7 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) for (cell = nodes.head; cell; cell = cell->next) { - int remote_node_id = UNKNOWN_NODE_ID; + int remote_node_id = UNKNOWN_NODE_ID; PQExpBufferData command; PQExpBufferData command_output; @@ -1155,14 +1170,14 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) /* fix to work with --node-id */ if (cube[i]->node_id == config_file_options.node_id) { - (void)local_command( - command.data, - &command_output); + (void) local_command( + command.data, + &command_output); } else { t_conninfo_param_list remote_conninfo; - char *host = NULL; + char *host = NULL; PQExpBufferData quoted_command; initPQExpBuffer("ed_command); @@ -1181,11 +1196,11 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) log_verbose(LOG_DEBUG, "build_cluster_crosscheck(): executing\n %s", quoted_command.data); - (void)remote_command( - host, - runtime_options.remote_user, - quoted_command.data, - &command_output); + (void) remote_command( + host, + runtime_options.remote_user, + quoted_command.data, + &command_output); free_conninfo_params(&remote_conninfo); termPQExpBuffer("ed_command); @@ -1195,7 +1210,7 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) p = command_output.data; - if(!strlen(command_output.data)) + if (!strlen(command_output.data)) { termPQExpBuffer(&command_output); continue; @@ -1203,9 +1218,9 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) for (j = 0; j < (nodes.node_count * nodes.node_count); j++) { - int matrix_rec_node_id; - int node_status_node_id; - int node_status; + int matrix_rec_node_id; + int node_status_node_id; + int node_status; if (sscanf(p, "%d,%d,%d", &matrix_rec_node_id, &node_status_node_id, &node_status) != 3) { @@ -1243,7 +1258,9 @@ build_cluster_crosscheck(t_node_status_cube ***dest_cube, int *name_length) static void cube_set_node_status(t_node_status_cube **cube, int n, int execute_node_id, int matrix_node_id, int connection_node_id, int connection_status) { - int h, i, j; + int h, + i, + j; for (h = 0; h < n; h++) diff --git a/repmgr-action-cluster.h b/repmgr-action-cluster.h index fc45fbb0..0927e86c 100644 --- a/repmgr-action-cluster.h +++ b/repmgr-action-cluster.h @@ -23,21 +23,21 @@ typedef struct { - int node_id; - int node_status; + int node_id; + int node_status; } t_node_status_rec; typedef struct { - int node_id; - char node_name[MAXLEN]; + int node_id; + char node_name[MAXLEN]; t_node_status_rec **node_status_list; } t_node_matrix_rec; typedef struct { - int node_id; - char node_name[MAXLEN]; + int node_id; + char node_name[MAXLEN]; t_node_matrix_rec **matrix_list_rec; } t_node_status_cube; diff --git a/repmgr-action-node.c b/repmgr-action-node.c index baae97c8..c97d81d8 100644 --- a/repmgr-action-node.c +++ b/repmgr-action-node.c @@ -16,7 +16,7 @@ * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License - * along with this program. If not, see . + * along with this program. If not, see . */ #include @@ -62,22 +62,22 @@ static CheckStatus do_node_check_slots(PGconn *conn, OutputMode mode, t_node_inf void do_node_status(void) { - PGconn *conn = NULL; + PGconn *conn = NULL; - t_node_info node_info = T_NODE_INFO_INITIALIZER; - char server_version[MAXLEN]; - char cluster_size[MAXLEN]; - PQExpBufferData output; + t_node_info node_info = T_NODE_INFO_INITIALIZER; + char server_version[MAXLEN]; + char cluster_size[MAXLEN]; + PQExpBufferData output; - KeyValueList node_status = { NULL, NULL }; + KeyValueList node_status = {NULL, NULL}; KeyValueListCell *cell = NULL; - ItemList warnings = { NULL, NULL }; - RecoveryType recovery_type = RECTYPE_UNKNOWN; - ReplInfo replication_info = T_REPLINFO_INTIALIZER; + ItemList warnings = {NULL, NULL}; + RecoveryType recovery_type = RECTYPE_UNKNOWN; + ReplInfo replication_info = T_REPLINFO_INTIALIZER; t_recovery_conf recovery_conf = T_RECOVERY_CONF_INITIALIZER; - char data_dir[MAXPGPATH] = ""; + char data_dir[MAXPGPATH] = ""; if (runtime_options.is_shutdown_cleanly == true) { @@ -109,36 +109,36 @@ do_node_status(void) get_node_replication_stats(conn, &node_info); key_value_list_set( - &node_status, - "PostgreSQL version", - server_version); + &node_status, + "PostgreSQL version", + server_version); key_value_list_set( - &node_status, - "Total data size", - cluster_size); + &node_status, + "Total data size", + cluster_size); key_value_list_set( - &node_status, - "Conninfo", - node_info.conninfo); + &node_status, + "Conninfo", + node_info.conninfo); if (runtime_options.verbose == true) { - uint64 local_system_identifier = UNKNOWN_SYSTEM_IDENTIFIER; + uint64 local_system_identifier = UNKNOWN_SYSTEM_IDENTIFIER; local_system_identifier = get_system_identifier(config_file_options.data_directory); key_value_list_set_format( - &node_status, - "System identifier", - "%lu", local_system_identifier); + &node_status, + "System identifier", + "%lu", local_system_identifier); } key_value_list_set( - &node_status, - "Role", - get_node_type_string(node_info.type)); + &node_status, + "Role", + get_node_type_string(node_info.type)); switch (node_info.type) { @@ -146,16 +146,16 @@ do_node_status(void) if (recovery_type == RECTYPE_STANDBY) { item_list_append( - &warnings, - _("- node is registered as primary but running as standby")); + &warnings, + _("- node is registered as primary but running as standby")); } break; case STANDBY: if (recovery_type == RECTYPE_PRIMARY) { item_list_append( - &warnings, - _("- node is registered as standby but running as primary")); + &warnings, + _("- node is registered as standby but running as primary")); } break; case BDR: @@ -166,20 +166,20 @@ do_node_status(void) if (guc_set(conn, "archive_mode", "=", "off")) { key_value_list_set( - &node_status, - "WAL archiving", - "off"); + &node_status, + "WAL archiving", + "off"); key_value_list_set( - &node_status, - "Archive command", - "(none)"); + &node_status, + "Archive command", + "(none)"); } else { - bool enabled = true; + bool enabled = true; PQExpBufferData archiving_status; - char archive_command[MAXLEN] = ""; + char archive_command[MAXLEN] = ""; initPQExpBuffer(&archiving_status); if (recovery_type == RECTYPE_STANDBY) @@ -203,40 +203,40 @@ do_node_status(void) } key_value_list_set( - &node_status, - "WAL archiving", - archiving_status.data); + &node_status, + "WAL archiving", + archiving_status.data); termPQExpBuffer(&archiving_status); get_pg_setting(conn, "archive_command", archive_command); key_value_list_set( - &node_status, - "Archive command", - archive_command); + &node_status, + "Archive command", + archive_command); } { - int ready_files; + int ready_files; ready_files = get_ready_archive_files(conn, data_dir); if (runtime_options.output_mode == OM_CSV) { key_value_list_set_format( - &node_status, - "WALs pending archiving", - "%i", - ready_files); + &node_status, + "WALs pending archiving", + "%i", + ready_files); } else { key_value_list_set_format( - &node_status, - "WALs pending archiving", - "%i pending files", - ready_files); + &node_status, + "WALs pending archiving", + "%i pending files", + ready_files); } if (guc_set(conn, "archive_mode", "=", "off")) @@ -251,111 +251,112 @@ do_node_status(void) { /* In CSV mode, raw values supplied as well */ key_value_list_set_format( - &node_status, - "Replication connections", - "%i (of maximal %i)", - node_info.attached_wal_receivers, - node_info.max_wal_senders); + &node_status, + "Replication connections", + "%i (of maximal %i)", + node_info.attached_wal_receivers, + node_info.max_wal_senders); } else if (node_info.max_wal_senders == 0) { key_value_list_set_format( - &node_status, - "Replication connections", - "disabled"); + &node_status, + "Replication connections", + "disabled"); } if (node_info.max_replication_slots > 0) { - PQExpBufferData slotinfo; + PQExpBufferData slotinfo; + initPQExpBuffer(&slotinfo); appendPQExpBuffer( - &slotinfo, - "%i (of maximal %i)", - node_info.active_replication_slots + node_info.inactive_replication_slots, - node_info.max_replication_slots); + &slotinfo, + "%i (of maximal %i)", + node_info.active_replication_slots + node_info.inactive_replication_slots, + node_info.max_replication_slots); if (node_info.inactive_replication_slots > 0) { appendPQExpBuffer( - &slotinfo, - "; %i inactive", - node_info.inactive_replication_slots); + &slotinfo, + "; %i inactive", + node_info.inactive_replication_slots); item_list_append_format( - &warnings, - _("- node has %i inactive replication slots"), - node_info.inactive_replication_slots); + &warnings, + _("- node has %i inactive replication slots"), + node_info.inactive_replication_slots); } key_value_list_set( - &node_status, - "Replication slots", - slotinfo.data); + &node_status, + "Replication slots", + slotinfo.data); termPQExpBuffer(&slotinfo); } else if (node_info.max_replication_slots == 0) { key_value_list_set( - &node_status, - "Replication slots", - "disabled"); + &node_status, + "Replication slots", + "disabled"); } if (node_info.type == STANDBY) { key_value_list_set_format( - &node_status, - "Upstream node", - "%s (ID: %i)", - node_info.node_name, - node_info.node_id); + &node_status, + "Upstream node", + "%s (ID: %i)", + node_info.node_name, + node_info.node_id); get_replication_info(conn, &replication_info); key_value_list_set_format( - &node_status, - "Replication lag", - "%i seconds", - replication_info.replication_lag_time); + &node_status, + "Replication lag", + "%i seconds", + replication_info.replication_lag_time); key_value_list_set_format( - &node_status, - "Last received LSN", - "%X/%X", format_lsn(replication_info.last_wal_receive_lsn)); + &node_status, + "Last received LSN", + "%X/%X", format_lsn(replication_info.last_wal_receive_lsn)); key_value_list_set_format( - &node_status, - "Last replayed LSN", - "%X/%X", format_lsn(replication_info.last_wal_replay_lsn)); + &node_status, + "Last replayed LSN", + "%X/%X", format_lsn(replication_info.last_wal_replay_lsn)); } else { key_value_list_set( - &node_status, - "Upstream node", - "(none)"); + &node_status, + "Upstream node", + "(none)"); key_value_list_set_output_mode(&node_status, "Upstream node", OM_CSV); key_value_list_set( - &node_status, - "Replication lag", - "n/a"); + &node_status, + "Replication lag", + "n/a"); key_value_list_set( - &node_status, - "Last received LSN", - "(none)"); + &node_status, + "Last received LSN", + "(none)"); key_value_list_set_output_mode(&node_status, "Last received LSN", OM_CSV); key_value_list_set( - &node_status, - "Last replayed LSN", - "(none)"); + &node_status, + "Last replayed LSN", + "(none)"); key_value_list_set_output_mode(&node_status, "Last replayed LSN", OM_CSV); } @@ -368,63 +369,63 @@ do_node_status(void) if (runtime_options.output_mode == OM_CSV) { appendPQExpBuffer( - &output, - "\"Node name\",\"%s\"\n", - node_info.node_name); + &output, + "\"Node name\",\"%s\"\n", + node_info.node_name); appendPQExpBuffer( - &output, - "\"Node ID\",\"%i\"\n", - node_info.node_id); + &output, + "\"Node ID\",\"%i\"\n", + node_info.node_id); for (cell = node_status.head; cell; cell = cell->next) { appendPQExpBuffer( - &output, - "\"%s\",\"%s\"\n", - cell->key, cell->value); + &output, + "\"%s\",\"%s\"\n", + cell->key, cell->value); } /* we'll add the raw data as well */ appendPQExpBuffer( - &output, - "\"max_wal_senders\",%i\n", - node_info.max_wal_senders); + &output, + "\"max_wal_senders\",%i\n", + node_info.max_wal_senders); appendPQExpBuffer( - &output, - "\"occupied_wal_senders\",%i\n", - node_info.attached_wal_receivers); + &output, + "\"occupied_wal_senders\",%i\n", + node_info.attached_wal_receivers); appendPQExpBuffer( - &output, - "\"max_replication_slots\",%i\n", - node_info.max_replication_slots); + &output, + "\"max_replication_slots\",%i\n", + node_info.max_replication_slots); appendPQExpBuffer( - &output, - "\"active_replication_slots\",%i\n", - node_info.active_replication_slots); + &output, + "\"active_replication_slots\",%i\n", + node_info.active_replication_slots); appendPQExpBuffer( - &output, - "\"inactive_replaction_slots\",%i\n", - node_info.inactive_replication_slots); + &output, + "\"inactive_replaction_slots\",%i\n", + node_info.inactive_replication_slots); } else { appendPQExpBuffer( - &output, - "Node \"%s\":\n", - node_info.node_name); + &output, + "Node \"%s\":\n", + node_info.node_name); for (cell = node_status.head; cell; cell = cell->next) { if (cell->output_mode == OM_NOT_SET) appendPQExpBuffer( - &output, - "\t%s: %s\n", cell->key, cell->value); + &output, + "\t%s: %s\n", cell->key, cell->value); } } @@ -456,21 +457,22 @@ do_node_status(void) */ static -void _do_node_status_is_shutdown_cleanly(void) +void +_do_node_status_is_shutdown_cleanly(void) { - PGPing ping_status; + PGPing ping_status; PQExpBufferData output; - DBState db_state; - XLogRecPtr checkPoint = InvalidXLogRecPtr; + DBState db_state; + XLogRecPtr checkPoint = InvalidXLogRecPtr; - NodeStatus node_status = NODE_STATUS_UNKNOWN; + NodeStatus node_status = NODE_STATUS_UNKNOWN; initPQExpBuffer(&output); appendPQExpBuffer( - &output, - "--state="); + &output, + "--state="); /* sanity-check we're dealing with a PostgreSQL directory */ if (is_pg_dir(config_file_options.data_directory) == false) @@ -503,7 +505,10 @@ void _do_node_status_is_shutdown_cleanly(void) if (db_state != DB_SHUTDOWNED && db_state != DB_SHUTDOWNED_IN_RECOVERY) { - /* node is not running, but pg_controldata says it is - unclean shutdown */ + /* + * node is not running, but pg_controldata says it is - unclean + * shutdown + */ if (node_status != NODE_STATUS_UP) { node_status = NODE_STATUS_UNCLEAN_SHUTDOWN; @@ -517,7 +522,11 @@ void _do_node_status_is_shutdown_cleanly(void) { node_status = NODE_STATUS_UNKNOWN; } - /* if still "UNKNOWN" at this point, then the node must be cleanly shut down */ + + /* + * if still "UNKNOWN" at this point, then the node must be cleanly shut + * down + */ else if (node_status == NODE_STATUS_UNKNOWN) { node_status = NODE_STATUS_DOWN; @@ -552,12 +561,12 @@ void _do_node_status_is_shutdown_cleanly(void) void do_node_check(void) { - PGconn *conn = NULL; + PGconn *conn = NULL; PQExpBufferData output; - t_node_info node_info = T_NODE_INFO_INITIALIZER; + t_node_info node_info = T_NODE_INFO_INITIALIZER; - CheckStatusList status_list = { NULL, NULL }; + CheckStatusList status_list = {NULL, NULL}; CheckStatusListCell *cell = NULL; @@ -576,8 +585,9 @@ do_node_check(void) /* add replication statistics to node record */ get_node_replication_stats(conn, &node_info); - /* handle specific checks - * ====================== */ + /* + * handle specific checks ====================== + */ if (runtime_options.archive_ready == true) { (void) do_node_check_archive_ready(conn, runtime_options.output_mode, NULL); @@ -640,24 +650,24 @@ do_node_check(void) else { appendPQExpBuffer( - &output, - "Node \"%s\":\n", - node_info.node_name); + &output, + "Node \"%s\":\n", + node_info.node_name); for (cell = status_list.head; cell; cell = cell->next) { appendPQExpBuffer( - &output, - "\t%s: %s", - cell->item, - output_check_status(cell->status)); + &output, + "\t%s: %s", + cell->item, + output_check_status(cell->status)); if (strlen(cell->details)) { appendPQExpBuffer( - &output, - " (%s)", - cell->details); + &output, + " (%s)", + cell->details); } appendPQExpBuffer(&output, "\n"); } @@ -678,7 +688,7 @@ do_node_check_role(PGconn *conn, OutputMode mode, t_node_info *node_info, CheckS CheckStatus status = CHECK_STATUS_OK; PQExpBufferData details; - RecoveryType recovery_type = get_recovery_type(conn); + RecoveryType recovery_type = get_recovery_type(conn); if (mode == OM_CSV) { @@ -696,14 +706,14 @@ do_node_check_role(PGconn *conn, OutputMode mode, t_node_info *node_info, CheckS { status = CHECK_STATUS_CRITICAL; appendPQExpBuffer( - &details, - _("node is registered as primary but running as standby")); + &details, + _("node is registered as primary but running as standby")); } else { appendPQExpBuffer( - &details, - _("node is primary")); + &details, + _("node is primary")); } break; case STANDBY: @@ -711,41 +721,41 @@ do_node_check_role(PGconn *conn, OutputMode mode, t_node_info *node_info, CheckS { status = CHECK_STATUS_CRITICAL; appendPQExpBuffer( - &details, - _("node is registered as standby but running as primary")); + &details, + _("node is registered as standby but running as primary")); } else { appendPQExpBuffer( - &details, - _("node is standby")); + &details, + _("node is standby")); } break; case BDR: - { - PQExpBufferData output; - - initPQExpBuffer(&output); - if (is_bdr_db(conn, &output) == false) { - status = CHECK_STATUS_CRITICAL; - appendPQExpBuffer( - &details, - "%s", output.data); - } - termPQExpBuffer(&output); + PQExpBufferData output; - if (status == CHECK_STATUS_OK) - { - if (is_active_bdr_node(conn, node_info->node_name) == false) + initPQExpBuffer(&output); + if (is_bdr_db(conn, &output) == false) { status = CHECK_STATUS_CRITICAL; appendPQExpBuffer( - &details, - _("node is not an active BDR node")); + &details, + "%s", output.data); + } + termPQExpBuffer(&output); + + if (status == CHECK_STATUS_OK) + { + if (is_active_bdr_node(conn, node_info->node_name) == false) + { + status = CHECK_STATUS_CRITICAL; + appendPQExpBuffer( + &details, + _("node is not an active BDR node")); + } } } - } default: break; } @@ -792,26 +802,26 @@ do_node_check_slots(PGconn *conn, OutputMode mode, t_node_info *node_info, Check if (node_info->total_replication_slots == 0) { appendPQExpBuffer( - &details, - _("node has no replication slots")); + &details, + _("node has no replication slots")); } else if (node_info->inactive_replication_slots == 0) { appendPQExpBuffer( - &details, - _("%i of %i replication slots are active"), - node_info->total_replication_slots, - node_info->total_replication_slots); + &details, + _("%i of %i replication slots are active"), + node_info->total_replication_slots, + node_info->total_replication_slots); } else if (node_info->inactive_replication_slots > 0) { status = CHECK_STATUS_CRITICAL; appendPQExpBuffer( - &details, - _("%i of %i replication slots are inactive"), - node_info->inactive_replication_slots, - node_info->total_replication_slots); + &details, + _("%i of %i replication slots are inactive"), + node_info->inactive_replication_slots, + node_info->total_replication_slots); } switch (mode) @@ -849,7 +859,7 @@ do_node_check_slots(PGconn *conn, OutputMode mode, t_node_info *node_info, Check static CheckStatus do_node_check_archive_ready(PGconn *conn, OutputMode mode, CheckStatusList *list_output) { - int ready_archive_files = 0; + int ready_archive_files = 0; CheckStatus status = CHECK_STATUS_UNKNOWN; PQExpBufferData details; @@ -872,24 +882,24 @@ do_node_check_archive_ready(PGconn *conn, OutputMode mode, CheckStatusList *list { case OM_OPTFORMAT: appendPQExpBuffer( - &details, - "--files=%i --threshold=%i", - ready_archive_files, config_file_options.archive_ready_critical); + &details, + "--files=%i --threshold=%i", + ready_archive_files, config_file_options.archive_ready_critical); break; case OM_NAGIOS: appendPQExpBuffer( - &details, - "%i pending archive ready files | files=%i;%i;%i", - ready_archive_files, - ready_archive_files, - config_file_options.archive_ready_warning, - config_file_options.archive_ready_critical); + &details, + "%i pending archive ready files | files=%i;%i;%i", + ready_archive_files, + ready_archive_files, + config_file_options.archive_ready_warning, + config_file_options.archive_ready_critical); break; case OM_TEXT: appendPQExpBuffer( - &details, - "%i pending archive ready files, critical threshold: %i", - ready_archive_files, config_file_options.archive_ready_critical); + &details, + "%i pending archive ready files, critical threshold: %i", + ready_archive_files, config_file_options.archive_ready_critical); break; default: @@ -904,25 +914,25 @@ do_node_check_archive_ready(PGconn *conn, OutputMode mode, CheckStatusList *list { case OM_OPTFORMAT: appendPQExpBuffer( - &details, - "--files=%i --threshold=%i", - ready_archive_files, config_file_options.archive_ready_warning); + &details, + "--files=%i --threshold=%i", + ready_archive_files, config_file_options.archive_ready_warning); break; case OM_NAGIOS: appendPQExpBuffer( - &details, - "%i pending archive ready files | files=%i;%i;%i", - ready_archive_files, - ready_archive_files, - config_file_options.archive_ready_warning, - config_file_options.archive_ready_critical); + &details, + "%i pending archive ready files | files=%i;%i;%i", + ready_archive_files, + ready_archive_files, + config_file_options.archive_ready_warning, + config_file_options.archive_ready_critical); break; case OM_TEXT: appendPQExpBuffer( - &details, - "%i pending archive ready files (threshold: %i)", - ready_archive_files, config_file_options.archive_ready_warning); + &details, + "%i pending archive ready files (threshold: %i)", + ready_archive_files, config_file_options.archive_ready_warning); break; default: @@ -940,8 +950,8 @@ do_node_check_archive_ready(PGconn *conn, OutputMode mode, CheckStatusList *list case OM_NAGIOS: case OM_TEXT: appendPQExpBuffer( - &details, - "unable to check archive_status directory"); + &details, + "unable to check archive_status directory"); break; default: @@ -956,22 +966,22 @@ do_node_check_archive_ready(PGconn *conn, OutputMode mode, CheckStatusList *list { case OM_OPTFORMAT: appendPQExpBuffer( - &details, - "--files=%i", ready_archive_files); + &details, + "--files=%i", ready_archive_files); break; case OM_NAGIOS: appendPQExpBuffer( - &details, - "%i pending archive ready files | files=%i;%i;%i", - ready_archive_files, - ready_archive_files, - config_file_options.archive_ready_warning, - config_file_options.archive_ready_critical); + &details, + "%i pending archive ready files | files=%i;%i;%i", + ready_archive_files, + ready_archive_files, + config_file_options.archive_ready_warning, + config_file_options.archive_ready_critical); break; case OM_TEXT: appendPQExpBuffer( - &details, - "%i pending archive ready files", ready_archive_files); + &details, + "%i pending archive ready files", ready_archive_files); break; default: @@ -982,12 +992,12 @@ do_node_check_archive_ready(PGconn *conn, OutputMode mode, CheckStatusList *list switch (mode) { case OM_OPTFORMAT: - { - printf("--status=%s %s\n", - output_check_status(status), - details.data); - } - break; + { + printf("--status=%s %s\n", + output_check_status(status), + details.data); + } + break; case OM_NAGIOS: printf("REPMGR_ARCHIVE_READY %s: %s\n", output_check_status(status), @@ -1020,7 +1030,7 @@ static CheckStatus do_node_check_replication_lag(PGconn *conn, OutputMode mode, t_node_info *node_info, CheckStatusList *list_output) { CheckStatus status = CHECK_STATUS_OK; - int lag_seconds = 0; + int lag_seconds = 0; PQExpBufferData details; if (mode == OM_CSV) @@ -1038,20 +1048,20 @@ do_node_check_replication_lag(PGconn *conn, OutputMode mode, t_node_info *node_i { case OM_OPTFORMAT: appendPQExpBuffer( - &details, - "--lag=0"); + &details, + "--lag=0"); break; case OM_NAGIOS: appendPQExpBuffer( - &details, - "0 seconds | lag=0;%i;%i", - config_file_options.replication_lag_warning, - config_file_options.replication_lag_critical); + &details, + "0 seconds | lag=0;%i;%i", + config_file_options.replication_lag_warning, + config_file_options.replication_lag_critical); break; case OM_TEXT: appendPQExpBuffer( - &details, - "N/A - node is primary"); + &details, + "N/A - node is primary"); break; default: break; @@ -1071,24 +1081,24 @@ do_node_check_replication_lag(PGconn *conn, OutputMode mode, t_node_info *node_i { case OM_OPTFORMAT: appendPQExpBuffer( - &details, - "--lag=%i --threshold=%i", - lag_seconds, config_file_options.replication_lag_critical); + &details, + "--lag=%i --threshold=%i", + lag_seconds, config_file_options.replication_lag_critical); break; case OM_NAGIOS: appendPQExpBuffer( - &details, - "%i seconds | lag=%i;%i;%i", - lag_seconds, - lag_seconds, - config_file_options.replication_lag_warning, - config_file_options.replication_lag_critical); + &details, + "%i seconds | lag=%i;%i;%i", + lag_seconds, + lag_seconds, + config_file_options.replication_lag_warning, + config_file_options.replication_lag_critical); break; case OM_TEXT: appendPQExpBuffer( - &details, - "%i seconds, critical threshold: %i)", - lag_seconds, config_file_options.replication_lag_critical); + &details, + "%i seconds, critical threshold: %i)", + lag_seconds, config_file_options.replication_lag_critical); break; default: @@ -1103,24 +1113,24 @@ do_node_check_replication_lag(PGconn *conn, OutputMode mode, t_node_info *node_i { case OM_OPTFORMAT: appendPQExpBuffer( - &details, - "--lag=%i --threshold=%i", - lag_seconds, config_file_options.replication_lag_warning); + &details, + "--lag=%i --threshold=%i", + lag_seconds, config_file_options.replication_lag_warning); break; case OM_NAGIOS: appendPQExpBuffer( - &details, - "%i seconds | lag=%i;%i;%i", - lag_seconds, - lag_seconds, - config_file_options.replication_lag_warning, - config_file_options.replication_lag_critical); + &details, + "%i seconds | lag=%i;%i;%i", + lag_seconds, + lag_seconds, + config_file_options.replication_lag_warning, + config_file_options.replication_lag_critical); break; case OM_TEXT: appendPQExpBuffer( - &details, - "%i seconds, warning threshold: %i)", - lag_seconds, config_file_options.replication_lag_warning); + &details, + "%i seconds, warning threshold: %i)", + lag_seconds, config_file_options.replication_lag_warning); break; default: @@ -1138,8 +1148,8 @@ do_node_check_replication_lag(PGconn *conn, OutputMode mode, t_node_info *node_i case OM_NAGIOS: case OM_TEXT: appendPQExpBuffer( - &details, - "unable to query replication lag"); + &details, + "unable to query replication lag"); break; default: @@ -1154,24 +1164,24 @@ do_node_check_replication_lag(PGconn *conn, OutputMode mode, t_node_info *node_i { case OM_OPTFORMAT: appendPQExpBuffer( - &details, - "--lag=%i", - lag_seconds); + &details, + "--lag=%i", + lag_seconds); break; case OM_NAGIOS: appendPQExpBuffer( - &details, - "%i seconds | lag=%i;%i;%i", - lag_seconds, - lag_seconds, - config_file_options.replication_lag_warning, - config_file_options.replication_lag_critical); + &details, + "%i seconds | lag=%i;%i;%i", + lag_seconds, + lag_seconds, + config_file_options.replication_lag_warning, + config_file_options.replication_lag_critical); break; case OM_TEXT: appendPQExpBuffer( - &details, - "%i seconds", - lag_seconds); + &details, + "%i seconds", + lag_seconds); break; default: @@ -1183,12 +1193,12 @@ do_node_check_replication_lag(PGconn *conn, OutputMode mode, t_node_info *node_i switch (mode) { case OM_OPTFORMAT: - { - printf("--status=%s %s\n", - output_check_status(status), - details.data); - } - break; + { + printf("--status=%s %s\n", + output_check_status(status), + details.data); + } + break; case OM_NAGIOS: printf("REPMGR_REPLICATION_LAG %s: %s\n", output_check_status(status), @@ -1221,13 +1231,13 @@ do_node_check_replication_lag(PGconn *conn, OutputMode mode, t_node_info *node_i static CheckStatus do_node_check_downstream(PGconn *conn, OutputMode mode, CheckStatusList *list_output) { - NodeInfoList downstream_nodes = T_NODE_INFO_LIST_INITIALIZER; + NodeInfoList downstream_nodes = T_NODE_INFO_LIST_INITIALIZER; NodeInfoListCell *cell = NULL; - int missing_nodes_count = 0; - CheckStatus status = CHECK_STATUS_OK; - ItemList missing_nodes = { NULL, NULL }; - ItemList attached_nodes = { NULL, NULL }; - PQExpBufferData details; + int missing_nodes_count = 0; + CheckStatus status = CHECK_STATUS_OK; + ItemList missing_nodes = {NULL, NULL}; + ItemList attached_nodes = {NULL, NULL}; + PQExpBufferData details; initPQExpBuffer(&details); @@ -1237,7 +1247,7 @@ do_node_check_downstream(PGconn *conn, OutputMode mode, CheckStatusList *list_ou { if (is_downstream_node_attached(conn, cell->node_info->node_name) == false) { - missing_nodes_count ++; + missing_nodes_count++; item_list_append_format(&missing_nodes, "%s (ID: %i)", cell->node_info->node_name, @@ -1256,45 +1266,46 @@ do_node_check_downstream(PGconn *conn, OutputMode mode, CheckStatusList *list_ou { if (downstream_nodes.node_count == 0) appendPQExpBuffer( - &details, - "this node has no downstream nodes"); + &details, + "this node has no downstream nodes"); else appendPQExpBuffer( - &details, - "%i of %i downstream nodes attached", - downstream_nodes.node_count, - downstream_nodes.node_count); + &details, + "%i of %i downstream nodes attached", + downstream_nodes.node_count, + downstream_nodes.node_count); } else { ItemListCell *missing_cell = NULL; - bool first = true; + bool first = true; + status = CHECK_STATUS_CRITICAL; appendPQExpBuffer( - &details, - "%i of %i downstream nodes not attached", - missing_nodes_count, - downstream_nodes.node_count); + &details, + "%i of %i downstream nodes not attached", + missing_nodes_count, + downstream_nodes.node_count); if (mode != OM_NAGIOS) { appendPQExpBuffer( - &details, "; missing: "); + &details, "; missing: "); for (missing_cell = missing_nodes.head; missing_cell; missing_cell = missing_cell->next) { if (first == false) appendPQExpBuffer( - &details, - ", "); + &details, + ", "); else first = false; if (first == false) appendPQExpBuffer( - &details, - "%s", missing_cell->string); + &details, + "%s", missing_cell->string); } } } @@ -1302,51 +1313,52 @@ do_node_check_downstream(PGconn *conn, OutputMode mode, CheckStatusList *list_ou switch (mode) { case OM_NAGIOS: - { - - printf("REPMGR_DOWNSTREAM_SERVERS %s: %s | ", - output_check_status(status), - details.data); - - if (missing_nodes_count) { - ItemListCell *missing_cell = NULL; - bool first = true; - printf("missing: "); - for (missing_cell = missing_nodes.head; missing_cell; missing_cell = missing_cell->next) - { - if (first == false) - printf(", "); - else - first = false; + printf("REPMGR_DOWNSTREAM_SERVERS %s: %s | ", + output_check_status(status), + details.data); - if (first == false) - printf("%s", missing_cell->string); - } - } - - if (downstream_nodes.node_count - missing_nodes_count) - { - ItemListCell *attached_cell = NULL; - bool first = true; if (missing_nodes_count) - printf("; "); - printf("attached: "); - for (attached_cell = attached_nodes.head; attached_cell; attached_cell = attached_cell->next) { - if (first == false) - printf(", "); - else - first = false; + ItemListCell *missing_cell = NULL; + bool first = true; - if (first == false) - printf("%s", attached_cell->string); + printf("missing: "); + for (missing_cell = missing_nodes.head; missing_cell; missing_cell = missing_cell->next) + { + if (first == false) + printf(", "); + else + first = false; + + if (first == false) + printf("%s", missing_cell->string); + } } - } - printf("\n"); - } + if (downstream_nodes.node_count - missing_nodes_count) + { + ItemListCell *attached_cell = NULL; + bool first = true; + + if (missing_nodes_count) + printf("; "); + printf("attached: "); + for (attached_cell = attached_nodes.head; attached_cell; attached_cell = attached_cell->next) + { + if (first == false) + printf(", "); + else + first = false; + + if (first == false) + printf("%s", attached_cell->string); + } + } + printf("\n"); + + } break; case OM_TEXT: if (list_output != NULL) @@ -1376,8 +1388,8 @@ void do_node_service(void) { t_server_action action = ACTION_UNKNOWN; - char data_dir[MAXPGPATH] = ""; - char command[MAXLEN] = ""; + char data_dir[MAXPGPATH] = ""; + char command[MAXLEN] = ""; PQExpBufferData output; action = parse_server_action(runtime_options.action); @@ -1424,7 +1436,7 @@ do_node_service(void) } else { - PGconn *conn = NULL; + PGconn *conn = NULL; if (strlen(config_file_options.conninfo)) conn = establish_db_connection(config_file_options.conninfo, true); @@ -1433,7 +1445,7 @@ do_node_service(void) log_notice(_("issuing CHECKPOINT")); - // check superuser conn! + /* check superuser conn! */ checkpoint(conn); PQfinish(conn); @@ -1476,11 +1488,11 @@ _do_node_service_check(void) static void _do_node_service_list_actions(t_server_action action) { - char command[MAXLEN] = ""; + char command[MAXLEN] = ""; - char data_dir[MAXPGPATH] = ""; + char data_dir[MAXPGPATH] = ""; - bool data_dir_required = false; + bool data_dir_required = false; /* do we need to provide a data directory for any of the actions? */ if (data_dir_required_for_action(ACTION_START)) @@ -1572,20 +1584,20 @@ parse_server_action(const char *action_name) void do_node_rejoin(void) { - PGconn *upstream_conn = NULL; + PGconn *upstream_conn = NULL; RecoveryType upstream_recovery_type = RECTYPE_UNKNOWN; - DBState db_state; - PGPing status; - bool is_shutdown = true; + DBState db_state; + PGPing status; + bool is_shutdown = true; PQExpBufferData command; PQExpBufferData command_output; PQExpBufferData follow_output; struct stat statbuf; - char filebuf[MAXPGPATH] = ""; + char filebuf[MAXPGPATH] = ""; t_node_info primary_node_record = T_NODE_INFO_INITIALIZER; - bool success = true; + bool success = true; /* check node is not actually running */ @@ -1661,12 +1673,12 @@ do_node_rejoin(void) } /* - * Forcibly rewind node if requested (this is mainly for use when - * this action is being executed by "repmgr standby switchover") + * Forcibly rewind node if requested (this is mainly for use when this + * action is being executed by "repmgr standby switchover") */ if (runtime_options.force_rewind == true) { - int ret; + int ret; _do_node_archive_config(); @@ -1674,18 +1686,18 @@ do_node_rejoin(void) initPQExpBuffer(&command); appendPQExpBuffer( - &command, - "%s -D ", - make_pg_path("pg_rewind")); + &command, + "%s -D ", + make_pg_path("pg_rewind")); appendShellString( - &command, - config_file_options.data_directory); + &command, + config_file_options.data_directory); appendPQExpBuffer( - &command, - " --source-server='%s'", - primary_node_record.conninfo); + &command, + " --source-server='%s'", + primary_node_record.conninfo); log_notice(_("executing pg_rewind")); log_debug("pg_rewind command is:\n %s", @@ -1694,8 +1706,8 @@ do_node_rejoin(void) initPQExpBuffer(&command_output); ret = local_command( - command.data, - &command_output); + command.data, + &command_output); termPQExpBuffer(&command); @@ -1735,17 +1747,17 @@ do_node_rejoin(void) initPQExpBuffer(&follow_output); success = do_standby_follow_internal( - upstream_conn, - &primary_node_record, - &follow_output); + upstream_conn, + &primary_node_record, + &follow_output); create_event_notification( - upstream_conn, - &config_file_options, - config_file_options.node_id, - "node_rejoin", - success, - follow_output.data); + upstream_conn, + &config_file_options, + config_file_options.node_id, + "node_rejoin", + success, + follow_output.data); PQfinish(upstream_conn); @@ -1777,15 +1789,15 @@ do_node_rejoin(void) static void _do_node_archive_config(void) { - char archive_dir[MAXPGPATH]; + char archive_dir[MAXPGPATH]; struct stat statbuf; struct dirent *arcdir_ent; - DIR *arcdir; + DIR *arcdir; - KeyValueList config_files = { NULL, NULL }; + KeyValueList config_files = {NULL, NULL}; KeyValueListCell *cell = NULL; - int copied_count = 0; + int copied_count = 0; format_archive_dir(archive_dir); @@ -1811,8 +1823,8 @@ _do_node_archive_config(void) } - else if(!S_ISDIR(statbuf.st_mode)) - { + else if (!S_ISDIR(statbuf.st_mode)) + { log_error(_("\"%s\" exists but is not a directory"), archive_dir); exit(ERR_BAD_CONFIG); @@ -1830,12 +1842,12 @@ _do_node_archive_config(void) } /* - * attempt to remove any existing files in the directory - * TODO: collate problem files into list + * attempt to remove any existing files in the directory TODO: collate + * problem files into list */ while ((arcdir_ent = readdir(arcdir)) != NULL) { - char arcdir_ent_path[MAXPGPATH] = ""; + char arcdir_ent_path[MAXPGPATH] = ""; snprintf(arcdir_ent_path, MAXPGPATH, "%s/%s", @@ -1863,18 +1875,18 @@ _do_node_archive_config(void) * extract list of config files from --config-files */ { - int i = 0; - int j = 0; - int config_file_len = strlen(runtime_options.config_files); + int i = 0; + int j = 0; + int config_file_len = strlen(runtime_options.config_files); - char filenamebuf[MAXLEN] = ""; - char pathbuf[MAXPGPATH] = ""; + char filenamebuf[MAXLEN] = ""; + char pathbuf[MAXPGPATH] = ""; for (j = 0; j < config_file_len; j++) { if (runtime_options.config_files[j] == ',') { - int filename_len = j - i; + int filename_len = j - i; if (filename_len > MAXLEN) filename_len = MAXLEN - 1; @@ -1889,9 +1901,9 @@ _do_node_archive_config(void) filenamebuf); key_value_list_set( - &config_files, - filenamebuf, - pathbuf); + &config_files, + filenamebuf, + pathbuf); i = j + 1; } @@ -1905,16 +1917,16 @@ _do_node_archive_config(void) config_file_options.data_directory, filenamebuf); key_value_list_set( - &config_files, - filenamebuf, - pathbuf); + &config_files, + filenamebuf, + pathbuf); } } for (cell = config_files.head; cell; cell = cell->next) { - char dest_file[MAXPGPATH] = ""; + char dest_file[MAXPGPATH] = ""; snprintf(dest_file, MAXPGPATH, "%s/%s", @@ -1957,12 +1969,12 @@ _do_node_archive_config(void) static void _do_node_restore_config(void) { - char archive_dir[MAXPGPATH] = ""; + char archive_dir[MAXPGPATH] = ""; - DIR *arcdir; + DIR *arcdir; struct dirent *arcdir_ent; - int copied_count = 0; - bool copy_ok = true; + int copied_count = 0; + bool copy_ok = true; format_archive_dir(archive_dir); @@ -1979,8 +1991,8 @@ _do_node_restore_config(void) while ((arcdir_ent = readdir(arcdir)) != NULL) { struct stat statbuf; - char src_file_path[MAXPGPATH]; - char dest_file_path[MAXPGPATH]; + char src_file_path[MAXPGPATH]; + char dest_file_path[MAXPGPATH]; snprintf(src_file_path, MAXPGPATH, "%s/%s", @@ -2027,8 +2039,9 @@ _do_node_restore_config(void) } /* - * Finally, delete directory - it should be empty unless it's been interfered - * with for some reason, in which case manual intervention is required + * Finally, delete directory - it should be empty unless it's been + * interfered with for some reason, in which case manual intervention is + * required */ if (rmdir(archive_dir) != 0 && errno != EEXIST) { @@ -2063,8 +2076,9 @@ format_archive_dir(char *archive_dir) static bool copy_file(const char *src_file, const char *dest_file) { - FILE *ptr_old, *ptr_new; - int a = 0; + FILE *ptr_old, + *ptr_new; + int a = 0; ptr_old = fopen(src_file, "r"); ptr_new = fopen(dest_file, "w"); @@ -2080,7 +2094,7 @@ copy_file(const char *src_file, const char *dest_file) chmod(dest_file, S_IRUSR | S_IWUSR); - while(1) + while (1) { a = fgetc(ptr_old); diff --git a/repmgr-action-node.h b/repmgr-action-node.h index d9fa07a6..3e0ac400 100644 --- a/repmgr-action-node.h +++ b/repmgr-action-node.h @@ -28,4 +28,4 @@ extern void do_node_service(void); extern void do_node_help(void); -#endif /* _REPMGR_ACTION_NODE_H_ */ +#endif /* _REPMGR_ACTION_NODE_H_ */ diff --git a/repmgr-action-primary.c b/repmgr-action-primary.c index 33ca0b49..8a00c076 100644 --- a/repmgr-action-primary.c +++ b/repmgr-action-primary.c @@ -43,7 +43,7 @@ do_primary_register(void) bool record_created = false; - PQExpBufferData event_description; + PQExpBufferData event_description; log_info(_("connecting to primary database...")); @@ -83,8 +83,8 @@ do_primary_register(void) /* * In --dry-run mode we can't proceed any further as the following code - * attempts to query the repmgr metadata, which won't exist until - * the extension is installed + * attempts to query the repmgr metadata, which won't exist until the + * extension is installed */ if (runtime_options.dry_run == true) { @@ -100,7 +100,10 @@ do_primary_register(void) { if (current_primary_id != config_file_options.node_id) { - /* it's impossible to add a second primary to a streaming replication cluster */ + /* + * it's impossible to add a second primary to a streaming + * replication cluster + */ log_error(_("there is already an active registered primary (node ID: %i) in this cluster"), current_primary_id); PQfinish(primary_conn); PQfinish(conn); @@ -115,9 +118,10 @@ do_primary_register(void) begin_transaction(conn); /* - * Check for an active primary node record with a different ID. This shouldn't - * happen, but could do if an existing primary was shut down without being unregistered. - */ + * Check for an active primary node record with a different ID. This + * shouldn't happen, but could do if an existing primary was shut down + * without being unregistered. + */ current_primary_id = get_primary_node_id(conn); if (current_primary_id != NODE_NOT_FOUND && current_primary_id != config_file_options.node_id) { @@ -130,8 +134,8 @@ do_primary_register(void) } /* - * Check whether there's an existing record for this node, and - * update it if --force set + * Check whether there's an existing record for this node, and update it + * if --force set */ record_status = get_node_record(conn, config_file_options.node_id, &node_info); @@ -199,12 +203,12 @@ do_primary_register(void) /* Log the event */ create_event_notification( - conn, - &config_file_options, - config_file_options.node_id, - "primary_register", - record_created, - event_description.data); + conn, + &config_file_options, + config_file_options.node_id, + "primary_register", + record_created, + event_description.data); termPQExpBuffer(&event_description); @@ -241,12 +245,12 @@ do_primary_register(void) void do_primary_unregister(void) { - PGconn *primary_conn = NULL; - PGconn *local_conn = NULL; - t_node_info local_node_info = T_NODE_INFO_INITIALIZER; + PGconn *primary_conn = NULL; + PGconn *local_conn = NULL; + t_node_info local_node_info = T_NODE_INFO_INITIALIZER; t_node_info *target_node_info_ptr = NULL; - PGconn *target_node_conn = NULL; + PGconn *target_node_conn = NULL; NodeInfoList downstream_nodes = T_NODE_INFO_LIST_INITIALIZER; @@ -257,8 +261,8 @@ do_primary_unregister(void) get_local_node_record(local_conn, config_file_options.node_id, &local_node_info); /* - * Obtain a connection to the current primary node - if this isn't possible, - * abort as we won't be able to update the "nodes" table anyway. + * Obtain a connection to the current primary node - if this isn't + * possible, abort as we won't be able to update the "nodes" table anyway. */ primary_conn = establish_primary_db_connection(local_conn, false); @@ -287,7 +291,7 @@ do_primary_unregister(void) /* Target node is local node? */ if (target_node_info.node_id == UNKNOWN_NODE_ID - || target_node_info.node_id == config_file_options.node_id) + || target_node_info.node_id == config_file_options.node_id) { target_node_info_ptr = &local_node_info; } @@ -306,7 +310,7 @@ do_primary_unregister(void) if (downstream_nodes.node_count > 0) { NodeInfoListCell *cell = NULL; - PQExpBufferData detail; + PQExpBufferData detail; if (downstream_nodes.node_count == 1) { @@ -361,13 +365,16 @@ do_primary_unregister(void) /* If we can connect to the node, perform some sanity checks on it */ else { - bool can_unregister = true; + bool can_unregister = true; RecoveryType recovery_type = get_recovery_type(target_node_conn); /* Node appears to be a standby */ if (recovery_type == RECTYPE_STANDBY) { - /* We'll refuse to do anything unless the node record shows it as a primary */ + /* + * We'll refuse to do anything unless the node record shows it as + * a primary + */ if (target_node_info_ptr->type != PRIMARY) { log_error(_("node %s (ID: %i) is a %s, unable to unregister"), @@ -376,9 +383,11 @@ do_primary_unregister(void) get_node_type_string(target_node_info_ptr->type)); can_unregister = false; } + /* * If --F/--force not set, hint that it might be appropriate to - * register the node as a standby rather than unregister as primary + * register the node as a standby rather than unregister as + * primary */ else if (!runtime_options.force) { @@ -400,8 +409,8 @@ do_primary_unregister(void) } else if (recovery_type == RECTYPE_PRIMARY) { - t_node_info primary_node_info = T_NODE_INFO_INITIALIZER; - bool primary_record_found = false; + t_node_info primary_node_info = T_NODE_INFO_INITIALIZER; + bool primary_record_found = false; primary_record_found = get_primary_node_record(primary_conn, &primary_node_info); @@ -415,8 +424,10 @@ do_primary_unregister(void) PQfinish(primary_conn); exit(ERR_BAD_CONFIG); } - /* This appears to be the cluster primary - cowardly refuse - * to delete the record + + /* + * This appears to be the cluster primary - cowardly refuse to + * delete the record */ if (primary_node_info.node_id == target_node_info_ptr->node_id) { @@ -461,8 +472,8 @@ do_primary_unregister(void) else { PQExpBufferData event_details; - bool delete_success = delete_node_record(primary_conn, - target_node_info_ptr->node_id); + bool delete_success = delete_node_record(primary_conn, + target_node_info_ptr->node_id); if (delete_success == false) { @@ -488,11 +499,11 @@ do_primary_unregister(void) } create_event_notification(primary_conn, - &config_file_options, - config_file_options.node_id, - "primary_unregister", - true, - event_details.data); + &config_file_options, + config_file_options.node_id, + "primary_unregister", + true, + event_details.data); termPQExpBuffer(&event_details); log_info(_("node %s (ID: %i) was successfully unregistered"), diff --git a/repmgr-action-standby.c b/repmgr-action-standby.c index 0f2be0b1..ad1a7341 100644 --- a/repmgr-action-standby.c +++ b/repmgr-action-standby.c @@ -37,7 +37,7 @@ typedef struct TablespaceDataListCell char *oid; char *location; /* optional payload */ - FILE *f; + FILE *f; } TablespaceDataListCell; typedef struct TablespaceDataList @@ -47,44 +47,44 @@ typedef struct TablespaceDataList } TablespaceDataList; -static PGconn *primary_conn = NULL; -static PGconn *source_conn = NULL; +static PGconn *primary_conn = NULL; +static PGconn *source_conn = NULL; -static char local_data_directory[MAXPGPATH] = ""; -static bool local_data_directory_provided = false; +static char local_data_directory[MAXPGPATH] = ""; +static bool local_data_directory_provided = false; -static bool upstream_conninfo_found = false; -static int upstream_node_id = UNKNOWN_NODE_ID; -static char upstream_data_directory[MAXPGPATH]; +static bool upstream_conninfo_found = false; +static int upstream_node_id = UNKNOWN_NODE_ID; +static char upstream_data_directory[MAXPGPATH]; static t_conninfo_param_list recovery_conninfo; -static char recovery_conninfo_str[MAXLEN] = ""; -static char upstream_repluser[NAMEDATALEN] = ""; +static char recovery_conninfo_str[MAXLEN] = ""; +static char upstream_repluser[NAMEDATALEN] = ""; -static int source_server_version_num = UNKNOWN_SERVER_VERSION_NUM; +static int source_server_version_num = UNKNOWN_SERVER_VERSION_NUM; static t_configfile_list config_files = T_CONFIGFILE_LIST_INITIALIZER; static standy_clone_mode mode = pg_basebackup; /* used by barman mode */ -static char local_repmgr_tmp_directory[MAXPGPATH]; -static char datadir_list_filename[MAXLEN]; -static char barman_command_buf[MAXLEN] = ""; +static char local_repmgr_tmp_directory[MAXPGPATH]; +static char datadir_list_filename[MAXLEN]; +static char barman_command_buf[MAXLEN] = ""; static void _do_standby_promote_internal(PGconn *conn, const char *data_dir); static void check_barman_config(void); -static void check_source_server(void); -static void check_source_server_via_barman(void); +static void check_source_server(void); +static void check_source_server_via_barman(void); static bool check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_info, bool exit_on_error); static void check_primary_standby_version_match(PGconn *conn, PGconn *primary_conn); static void check_recovery_type(PGconn *conn); static void initialise_direct_clone(t_node_info *node_record); -static int run_basebackup(t_node_info *node_record); -static int run_file_backup(t_node_info *node_record); +static int run_basebackup(t_node_info *node_record); +static int run_file_backup(t_node_info *node_record); static void copy_configuration_files(void); @@ -93,7 +93,7 @@ static void drop_replication_slot_if_exists(PGconn *conn, int node_id, char *slo static void tablespace_data_append(TablespaceDataList *list, const char *name, const char *oid, const char *location); static void get_barman_property(char *dst, char *name, char *local_repmgr_directory); -static int get_tablespace_data_barman(char *, TablespaceDataList *); +static int get_tablespace_data_barman(char *, TablespaceDataList *); static char *make_barman_ssh_command(char *buf); static NodeStatus parse_node_status_is_shutdown_cleanly(const char *node_status_output, XLogRecPtr *checkPoint); @@ -122,7 +122,7 @@ void do_standby_clone(void) { PQExpBufferData event_details; - int r = 0; + int r = 0; /* dummy node record */ t_node_info node_record = T_NODE_INFO_INITIALIZER; @@ -136,15 +136,15 @@ do_standby_clone(void) /* * Copy the provided data directory; if a configuration file was provided, - * use the (mandatory) value from that; if -D/--pgdata was provided, use that; - * otherwise repmgr will default to using the same directory path as on the - * source host. The last case will only ever occur when executing "repmgr - * standby clone" with no configuration file. + * use the (mandatory) value from that; if -D/--pgdata was provided, use + * that; otherwise repmgr will default to using the same directory path as + * on the source host. The last case will only ever occur when executing + * "repmgr standby clone" with no configuration file. * * Note that barman mode requires -D/--pgdata. * - * If no data directory is explicitly provided, and we're not cloning from barman, - * the source host's data directory will be fetched later, after + * If no data directory is explicitly provided, and we're not cloning from + * barman, the source host's data directory will be fetched later, after * we've connected to it, in check_source_server(). * */ @@ -158,7 +158,8 @@ do_standby_clone(void) } else if (mode == barman) { - /* XXX in Barman mode it's still possible to connect to the upstream, + /* + * XXX in Barman mode it's still possible to connect to the upstream, * so only fail if that's not available. */ log_error(_("Barman mode requires a data directory")); @@ -177,15 +178,14 @@ do_standby_clone(void) node_record.type = STANDBY; /* - * Initialise list of conninfo parameters which will later be used - * to create the `primary_conninfo` string in recovery.conf . + * Initialise list of conninfo parameters which will later be used to + * create the `primary_conninfo` string in recovery.conf . * * We'll initialise it with the host settings specified on the command * line. As it's possible the standby will be cloned from a node different - * to its intended upstream, we'll later attempt to fetch the - * upstream node record and overwrite the values set here with - * those from the upstream node record (excluding that record's - * application_name) + * to its intended upstream, we'll later attempt to fetch the upstream + * node record and overwrite the values set here with those from the + * upstream node record (excluding that record's application_name) */ initialize_conninfo_params(&recovery_conninfo, false); @@ -195,7 +195,7 @@ do_standby_clone(void) /* Set the default application name to this node's name */ if (config_file_options.node_id != UNKNOWN_NODE_ID) { - char application_name[MAXLEN] = ""; + char application_name[MAXLEN] = ""; param_set(&recovery_conninfo, "application_name", config_file_options.node_name); @@ -207,35 +207,38 @@ do_standby_clone(void) } else { - /* this will only happen in corner cases where the node is being - * cloned without a configuration file; fall back to "repmgr" if no application_name - * provided + /* + * this will only happen in corner cases where the node is being + * cloned without a configuration file; fall back to "repmgr" if no + * application_name provided */ - char *application_name = param_get(&source_conninfo, "application_name"); + char *application_name = param_get(&source_conninfo, "application_name"); if (application_name == NULL) param_set(&recovery_conninfo, "application_name", "repmgr"); } /* - * By default attempt to connect to the source node. This will fail - * if no connection is possible, unless in Barman mode, in which case - * we can fall back to connecting to the source node via Barman. + * By default attempt to connect to the source node. This will fail if no + * connection is possible, unless in Barman mode, in which case we can + * fall back to connecting to the source node via Barman. */ if (runtime_options.no_upstream_connection == false) { /* * This connects to the source node and performs sanity checks, also - * sets "recovery_conninfo_str", "upstream_repluser" and "upstream_node_id". + * sets "recovery_conninfo_str", "upstream_repluser" and + * "upstream_node_id". * - * Will error out if source connection not possible and not in "barman" mode. + * Will error out if source connection not possible and not in + * "barman" mode. */ check_source_server(); } /* - * if --upstream-conninfo was supplied, use that (will overwrite - * value set by check_source_server(), but that's OK) + * if --upstream-conninfo was supplied, use that (will overwrite value set + * by check_source_server(), but that's OK) */ if (runtime_options.upstream_conninfo[0] != '\0') { @@ -245,16 +248,17 @@ do_standby_clone(void) else if (mode == barman && PQstatus(source_conn) != CONNECTION_OK) { /* - * Here we don't have a connection to the upstream node (either because - * --no-upstream-connection was supplied, or check_source_server() was unable - * to make a connection, and --upstream-conninfo wasn't supplied. + * Here we don't have a connection to the upstream node (either + * because --no-upstream-connection was supplied, or + * check_source_server() was unable to make a connection, and + * --upstream-conninfo wasn't supplied. * - * As we're executing in Barman mode we can try and connect via the Barman server - * to extract the upstream node's conninfo string. + * As we're executing in Barman mode we can try and connect via the + * Barman server to extract the upstream node's conninfo string. * - * To do this we need to extract Barman's conninfo string, replace the database - * name with the repmgr one (they could well be different) and remotely execute - * psql. + * To do this we need to extract Barman's conninfo string, replace the + * database name with the repmgr one (they could well be different) + * and remotely execute psql. * * This attempts to set "recovery_conninfo_str". */ @@ -266,17 +270,17 @@ do_standby_clone(void) log_error(_("unable to determine a connection string to use as \"primary_conninfo\"")); log_hint(_("use \"--upstream-conninfo\" to explicitly provide a value for \"primary_conninfo\"")); if (PQstatus(source_conn) == CONNECTION_OK) - PQfinish(source_conn); + PQfinish(source_conn); exit(ERR_BAD_CONFIG); } /* - * by this point we should know the target data directory - check - * there's no running Pg instance + * by this point we should know the target data directory - check there's + * no running Pg instance */ if (is_pg_dir(local_data_directory)) { - DBState state = get_db_state(local_data_directory); + DBState state = get_db_state(local_data_directory); if (state != DB_SHUTDOWNED && state != DB_SHUTDOWNED_IN_RECOVERY) { @@ -288,13 +292,19 @@ do_standby_clone(void) if (upstream_conninfo_found == true) { - /* parse returned upstream conninfo string to recovery primary_conninfo params */ + /* + * parse returned upstream conninfo string to recovery + * primary_conninfo params + */ char *errmsg = NULL; - bool parse_success = false; + bool parse_success = false; log_verbose(LOG_DEBUG, "parsing upstream conninfo string \"%s\"", recovery_conninfo_str); - /* parse_conninfo_string() here will remove the upstream's `application_name`, if set */ + /* + * parse_conninfo_string() here will remove the upstream's + * `application_name`, if set + */ parse_success = parse_conninfo_string(recovery_conninfo_str, &recovery_conninfo, errmsg, true); @@ -308,7 +318,7 @@ do_standby_clone(void) exit(ERR_BAD_CONFIG); } - if (upstream_repluser[0] != '\0') + if (upstream_repluser[0] != '\0') { /* Write the replication user from the node's upstream record */ param_set(&recovery_conninfo, "user", upstream_repluser); @@ -319,8 +329,8 @@ do_standby_clone(void) /* * If no upstream node record found, we'll abort with an error here, * unless -F/--force is used, in which case we'll use the parameters - * provided on the command line (and assume the user knows what they're - * doing). + * provided on the command line (and assume the user knows what + * they're doing). */ if (upstream_node_id == UNKNOWN_NODE_ID) { @@ -346,11 +356,12 @@ do_standby_clone(void) * If copying of external configuration files requested, and any are * detected, perform sanity checks */ - if (PQstatus(source_conn) == CONNECTION_OK) { - PGconn *superuser_conn = NULL; - PGconn *privileged_conn = NULL; - bool external_config_files = false; - int i = 0; + if (PQstatus(source_conn) == CONNECTION_OK) + { + PGconn *superuser_conn = NULL; + PGconn *privileged_conn = NULL; + bool external_config_files = false; + int i = 0; /* * Obtain configuration file locations @@ -359,14 +370,14 @@ do_standby_clone(void) * directory - if not we'll have to copy them via SSH, if copying * requested. * - * This will require superuser permissions, so we'll attempt to connect - * as -S/--superuser (if provided), otherwise check the current connection - * user has superuser rights. + * This will require superuser permissions, so we'll attempt to + * connect as -S/--superuser (if provided), otherwise check the + * current connection user has superuser rights. * - * XXX: if configuration files are symlinks to targets outside the data - * directory, they won't be copied by pg_basebackup, but we can't tell - * this from the below query; we'll probably need to add a check for their - * presence and if missing force copy by SSH + * XXX: if configuration files are symlinks to targets outside the + * data directory, they won't be copied by pg_basebackup, but we can't + * tell this from the below query; we'll probably need to add a check + * for their presence and if missing force copy by SSH */ get_superuser_connection(&source_conn, &superuser_conn, &privileged_conn); @@ -395,7 +406,7 @@ do_standby_clone(void) if (external_config_files == true) { - int r; + int r; PQExpBufferData msg; initPQExpBuffer(&msg); @@ -419,7 +430,7 @@ do_standby_clone(void) if (r != 0) { log_error(_("remote host \"%s\" is not reachable via SSH - unable to copy external configuration files"), - runtime_options.host); + runtime_options.host); if (superuser_conn != NULL) PQfinish(superuser_conn); PQfinish(source_conn); @@ -529,8 +540,8 @@ do_standby_clone(void) /* * If `--copy-external-config-files` was provided, copy any configuration - * files detected to the appropriate location. Any errors encountered - * will not be treated as fatal. + * files detected to the appropriate location. Any errors encountered will + * not be treated as fatal. * * This won't run in Barman mode as "config_files" is only populated in * "initialise_direct_clone()", which isn't called in Barman mode. @@ -553,7 +564,7 @@ do_standby_clone(void) exit(ERR_BAD_CONFIG); } - switch(mode) + switch (mode) { case pg_basebackup: log_notice(_("standby clone (using pg_basebackup) complete")); @@ -565,8 +576,8 @@ do_standby_clone(void) } /* - * TODO: It might be nice to provide an option to have repmgr start - * the PostgreSQL server automatically + * TODO: It might be nice to provide an option to have repmgr start the + * PostgreSQL server automatically */ log_notice(_("you can now start your PostgreSQL server")); @@ -587,21 +598,20 @@ do_standby_clone(void) } /* - * XXX forgetting to (re) register the standby is a frequent cause - * of error; we should consider having repmgr automatically - * register the standby, either by default with an option - * "--no-register", or an option "--register". + * XXX forgetting to (re) register the standby is a frequent cause of + * error; we should consider having repmgr automatically register the + * standby, either by default with an option "--no-register", or an option + * "--register". * - * Note that "repmgr standby register" requires the standby to - * be running - if not, and we just update the node record, - * we'd have an incorrect representation of the replication cluster. - * Best combined with an automatic start of the server (see note - * above) + * Note that "repmgr standby register" requires the standby to be running + * - if not, and we just update the node record, we'd have an incorrect + * representation of the replication cluster. Best combined with an + * automatic start of the server (see note above) */ /* - * Check for an existing node record, and output the appropriate - * command for registering or re-registering. + * Check for an existing node record, and output the appropriate command + * for registering or re-registering. */ { t_node_info node_record = T_NODE_INFO_INITIALIZER; @@ -636,7 +646,7 @@ do_standby_clone(void) appendPQExpBuffer(&event_details, _("; backup method: ")); - switch(mode) + switch (mode) { case pg_basebackup: appendPQExpBuffer(&event_details, "pg_basebackup"); @@ -651,11 +661,11 @@ do_standby_clone(void) runtime_options.force ? "Y" : "N"); create_event_notification(primary_conn, - &config_file_options, - config_file_options.node_id, - "standby_clone", - true, - event_details.data); + &config_file_options, + config_file_options.node_id, + "standby_clone", + true, + event_details.data); if (primary_conn != source_conn && PQstatus(primary_conn) == CONNECTION_OK) PQfinish(primary_conn); @@ -681,7 +691,7 @@ check_barman_config(void) maxlen_snprintf(command, "%s show-backup %s latest > /dev/null", make_barman_ssh_command(barman_command_buf), - config_file_options.barman_server); + config_file_options.barman_server); command_ok = local_command(command, NULL); @@ -698,7 +708,7 @@ check_barman_config(void) if (!create_pg_dir(local_data_directory, runtime_options.force)) { log_error(_("unable to use directory %s"), - local_data_directory); + local_data_directory); log_hint(_("use -F/--force option to force this directory to be overwritten")); exit(ERR_BAD_CONFIG); } @@ -750,7 +760,7 @@ check_barman_config(void) * Event(s): * - standby_register */ -// XXX check --upstream-node-id works when re-registering +/* XXX check --upstream-node-id works when re-registering */ void do_standby_register(void) @@ -807,7 +817,11 @@ do_standby_register(void) { primary_conn = get_primary_connection(conn, NULL, NULL); } - /* User is forcing a registration and must have supplied primary connection info */ + + /* + * User is forcing a registration and must have supplied primary + * connection info + */ else { primary_conn = establish_db_connection_by_params(&source_conninfo, false); @@ -885,6 +899,7 @@ do_standby_register(void) { RecordStatus upstream_record_status = RECORD_NOT_FOUND; t_node_info upstream_node_record = T_NODE_INFO_INITIALIZER; + upstream_record_status = get_node_record(primary_conn, runtime_options.upstream_node_id, &upstream_node_record); @@ -920,14 +935,14 @@ do_standby_register(void) &placeholder_upstream_node_record); /* - * It's possible, in the kind of scenario this functionality is intended - * to support, that there's a race condition where the node's actual - * record gets inserted, causing the insert of the placeholder record - * to fail. If this is the case, we don't worry about this insert failing; - * if not we bail out. + * It's possible, in the kind of scenario this functionality is + * intended to support, that there's a race condition where the + * node's actual record gets inserted, causing the insert of the + * placeholder record to fail. If this is the case, we don't worry + * about this insert failing; if not we bail out. * - * TODO: teach create_node_record() to use ON CONFLICT DO NOTHING for - * 9.5 and later. + * TODO: teach create_node_record() to use ON CONFLICT DO NOTHING + * for 9.5 and later. */ if (record_created == false) { @@ -951,7 +966,8 @@ do_standby_register(void) else if (node_record.active == false) { /* - * upstream node is inactive and --force not supplied - refuse to register + * upstream node is inactive and --force not supplied - refuse to + * register */ if (!runtime_options.force) { @@ -974,7 +990,7 @@ do_standby_register(void) /* check upstream node is accessible and this node is connected */ else { - PGconn *upstream_conn = NULL; + PGconn *upstream_conn = NULL; upstream_conn = establish_db_connection(upstream_node_record.conninfo, false); @@ -1048,8 +1064,8 @@ do_standby_register(void) /* - * node record exists - update it - * (at this point we have already established that -F/--force is in use) + * node record exists - update it (at this point we have already + * established that -F/--force is in use) */ if (record_status == RECORD_FOUND) { @@ -1069,13 +1085,13 @@ do_standby_register(void) if (record_created == false) { appendPQExpBuffer( - &details, - "standby registration failed"); + &details, + "standby registration failed"); if (runtime_options.force == true) appendPQExpBuffer( - &details, - " (-F/--force option was used)"); + &details, + " (-F/--force option was used)"); create_event_notification(primary_conn, &config_file_options, @@ -1094,13 +1110,13 @@ do_standby_register(void) } appendPQExpBuffer( - &details, - "standby registration succeeded"); + &details, + "standby registration succeeded"); if (runtime_options.force == true) appendPQExpBuffer( - &details, - " (-F/--force option was used)"); + &details, + " (-F/--force option was used)"); /* Log the event */ @@ -1119,8 +1135,8 @@ do_standby_register(void) runtime_options.wait_register_sync == true && runtime_options.wait_register_sync_seconds > 0) { - bool sync_ok = false; - int timer = 0; + bool sync_ok = false; + int timer = 0; RecordStatus node_record_status = RECORD_NOT_FOUND; t_node_info node_record_on_primary = T_NODE_INFO_INITIALIZER; t_node_info node_record_on_standby = T_NODE_INFO_INITIALIZER; @@ -1139,7 +1155,7 @@ do_standby_register(void) for (;;) { - bool records_match = true; + bool records_match = true; if (runtime_options.wait_register_sync_seconds && runtime_options.wait_register_sync_seconds == timer) break; @@ -1150,7 +1166,7 @@ do_standby_register(void) if (node_record_status == RECORD_NOT_FOUND) { - /* no record available yet on standby*/ + /* no record available yet on standby */ records_match = false; } else if (node_record_status == RECORD_FOUND) @@ -1185,7 +1201,7 @@ do_standby_register(void) } sleep(1); - timer ++; + timer++; } if (sync_ok == false) @@ -1225,7 +1241,7 @@ do_standby_unregister(void) PGconn *conn = NULL; PGconn *primary_conn = NULL; - int target_node_id = UNKNOWN_NODE_ID; + int target_node_id = UNKNOWN_NODE_ID; t_node_info node_info = T_NODE_INFO_INITIALIZER; bool node_record_deleted = false; @@ -1275,7 +1291,7 @@ do_standby_unregister(void) /* Now unregister the standby */ log_notice(_("unregistering node %i"), target_node_id); node_record_deleted = delete_node_record(primary_conn, - target_node_id); + target_node_id); if (node_record_deleted == false) { @@ -1286,11 +1302,11 @@ do_standby_unregister(void) /* Log the event */ create_event_notification(primary_conn, - &config_file_options, - target_node_id, - "standby_unregister", - true, - NULL); + &config_file_options, + target_node_id, + "standby_unregister", + true, + NULL); PQfinish(primary_conn); PQfinish(conn); @@ -1379,7 +1395,7 @@ _do_standby_promote_internal(PGconn *conn, const char *data_dir) char script[MAXLEN]; int r; int i, - promote_check_timeout = 60, + promote_check_timeout = 60, promote_check_interval = 2; bool promote_success = false; PQExpBufferData details; @@ -1398,7 +1414,7 @@ _do_standby_promote_internal(PGconn *conn, const char *data_dir) if (record_status != RECORD_FOUND) { log_error(_("unable to retrieve record for node %i"), - config_file_options.node_id); + config_file_options.node_id); PQfinish(conn); exit(ERR_BAD_CONFIG); } @@ -1407,12 +1423,12 @@ _do_standby_promote_internal(PGconn *conn, const char *data_dir) /* * Promote standby to primary. * - * `pg_ctl promote` returns immediately and (prior to 10.0) has no -w option - * so we can't be sure when or if the promotion completes. - * For now we'll poll the server until the default timeout (60 seconds) + * `pg_ctl promote` returns immediately and (prior to 10.0) has no -w + * option so we can't be sure when or if the promotion completes. For now + * we'll poll the server until the default timeout (60 seconds) */ - get_server_action(ACTION_PROMOTE, script, (char *)data_dir); + get_server_action(ACTION_PROMOTE, script, (char *) data_dir); log_notice(_("promoting standby to primary")); log_detail(_("promoting server \"%s\" (ID: %i) using \"%s\""), @@ -1468,11 +1484,11 @@ _do_standby_promote_internal(PGconn *conn, const char *data_dir) log_error("%s", details.data); create_event_notification(NULL, - &config_file_options, - config_file_options.node_id, - "standby_promote", - false, - details.data); + &config_file_options, + config_file_options.node_id, + "standby_promote", + false, + details.data); exit(ERR_DB_QUERY); } @@ -1489,11 +1505,11 @@ _do_standby_promote_internal(PGconn *conn, const char *data_dir) /* Log the event */ create_event_notification(conn, - &config_file_options, - config_file_options.node_id, - "standby_promote", - true, - details.data); + &config_file_options, + config_file_options.node_id, + "standby_promote", + true, + details.data); termPQExpBuffer(&details); @@ -1520,16 +1536,16 @@ do_standby_follow(void) PGconn *primary_conn = NULL; int primary_id = UNKNOWN_NODE_ID; t_node_info primary_node_record = T_NODE_INFO_INITIALIZER; - RecordStatus record_status = RECORD_NOT_FOUND; + RecordStatus record_status = RECORD_NOT_FOUND; - int timer = 0; + int timer = 0; PQExpBufferData follow_output; - bool success = false; + bool success = false; - uint64 local_system_identifier = UNKNOWN_SYSTEM_IDENTIFIER; + uint64 local_system_identifier = UNKNOWN_SYSTEM_IDENTIFIER; t_conninfo_param_list repl_conninfo; - PGconn *repl_conn = NULL; + PGconn *repl_conn = NULL; t_system_identification primary_identification = T_SYSTEM_IDENTIFICATION_INITIALIZER; log_verbose(LOG_DEBUG, "do_standby_follow()"); @@ -1579,8 +1595,8 @@ do_standby_follow(void) /* * Attempt to connect to primary. * - * If --wait provided, loop for up `primary_follow_timeout` - * seconds before giving up + * If --wait provided, loop for up `primary_follow_timeout` seconds + * before giving up */ for (timer = 0; timer < config_file_options.primary_follow_timeout; timer++) @@ -1616,7 +1632,7 @@ do_standby_follow(void) } - // XXX check this is not current upstream anyway + /* XXX check this is not current upstream anyway */ /* check replication connection */ initialize_conninfo_params(&repl_conninfo, false); @@ -1662,17 +1678,17 @@ do_standby_follow(void) initPQExpBuffer(&follow_output); success = do_standby_follow_internal( - primary_conn, - &primary_node_record, - &follow_output); + primary_conn, + &primary_node_record, + &follow_output); create_event_notification( - primary_conn, - &config_file_options, - config_file_options.node_id, - "standby_follow", - success, - follow_output.data); + primary_conn, + &config_file_options, + config_file_options.node_id, + "standby_follow", + success, + follow_output.data); PQfinish(primary_conn); @@ -1709,9 +1725,9 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor /* - * Fetch our node record so we can write application_name, if set, - * and to get the upstream node ID, which we'll need to know if - * replication slots are in use and we want to delete the old slot. + * Fetch our node record so we can write application_name, if set, and to + * get the upstream node ID, which we'll need to know if replication slots + * are in use and we want to delete the old slot. */ record_status = get_node_record(primary_conn, config_file_options.node_id, @@ -1720,19 +1736,19 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor if (record_status != RECORD_FOUND) { log_error(_("unable to retrieve record for node %i"), - config_file_options.node_id); + config_file_options.node_id); PQfinish(primary_conn); exit(ERR_BAD_CONFIG); } /* - * If replication slots are in use, we'll need to create a - * slot on the new primary + * If replication slots are in use, we'll need to create a slot on the new + * primary */ if (config_file_options.use_replication_slots) { - int primary_server_version_num = get_server_version(primary_conn, NULL); + int primary_server_version_num = get_server_version(primary_conn, NULL); if (create_replication_slot(primary_conn, local_node_record.slot_name, @@ -1753,7 +1769,7 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor { t_conninfo_param_list local_node_conninfo; - bool parse_success; + bool parse_success; initialize_conninfo_params(&local_node_conninfo, false); @@ -1761,21 +1777,24 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor if (parse_success == false) { - /* this shouldn't happen, but if it does we'll plough on regardless */ + /* + * this shouldn't happen, but if it does we'll plough on + * regardless + */ log_warning(_("unable to parse conninfo string \"%s\":\n %s"), local_node_record.conninfo, errmsg); } else { - char *application_name = param_get(&local_node_conninfo, "application_name"); + char *application_name = param_get(&local_node_conninfo, "application_name"); if (application_name != NULL && strlen(application_name)) param_set(&recovery_conninfo, "application_name", application_name); } /* - * store the original upstream node id so we can delete the replication slot, - * if exists + * store the original upstream node id so we can delete the + * replication slot, if exists */ if (local_node_record.upstream_node_id != UNKNOWN_NODE_ID) { @@ -1807,13 +1826,13 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor /* start/restart the service */ - // XXX here check if service is running!! if not, start + /* XXX here check if service is running!! if not, start */ { char server_command[MAXLEN] = ""; bool server_up = is_server_available(config_file_options.conninfo); char *action = NULL; - int r; + int r; if (server_up == true) { @@ -1850,7 +1869,7 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor if (config_file_options.use_replication_slots && runtime_options.host_param_provided == false && original_upstream_node_id != UNKNOWN_NODE_ID) { - t_node_info upstream_node_record = T_NODE_INFO_INITIALIZER; + t_node_info upstream_node_record = T_NODE_INFO_INITIALIZER; RecordStatus upstream_record_status = RECORD_NOT_FOUND; PGconn *local_conn = NULL; @@ -1861,8 +1880,8 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor local_conn = establish_db_connection(config_file_options.conninfo, true); upstream_record_status = get_node_record(local_conn, - original_upstream_node_id, - &upstream_node_record); + original_upstream_node_id, + &upstream_node_record); PQfinish(local_conn); @@ -1873,7 +1892,7 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor } else { - PGconn *old_upstream_conn = establish_db_connection_quiet(upstream_node_record.conninfo); + PGconn *old_upstream_conn = establish_db_connection_quiet(upstream_node_record.conninfo); if (PQstatus(old_upstream_conn) != CONNECTION_OK) { @@ -1891,8 +1910,8 @@ do_standby_follow_internal(PGconn *primary_conn, t_node_info *primary_node_recor } /* - * It's possible this node was an inactive primary - update the - * relevant fields to ensure it's marked as an active standby + * It's possible this node was an inactive primary - update the relevant + * fields to ensure it's marked as an active standby */ if (update_node_record_status(primary_conn, config_file_options.node_id, @@ -1945,35 +1964,36 @@ do_standby_switchover(void) t_node_info local_node_record = T_NODE_INFO_INITIALIZER; /* the remote server is the primary to be demoted */ - char remote_conninfo[MAXCONNINFO] = ""; - char remote_host[MAXLEN] = ""; - int remote_node_id = UNKNOWN_NODE_ID; + char remote_conninfo[MAXCONNINFO] = ""; + char remote_host[MAXLEN] = ""; + int remote_node_id = UNKNOWN_NODE_ID; t_node_info remote_node_record = T_NODE_INFO_INITIALIZER; - RecordStatus record_status = RECORD_NOT_FOUND; - RecoveryType recovery_type = RECTYPE_UNKNOWN; + RecordStatus record_status = RECORD_NOT_FOUND; + RecoveryType recovery_type = RECTYPE_UNKNOWN; PQExpBufferData remote_command_str; PQExpBufferData command_output; PQExpBufferData node_rejoin_options; - int r, i; + int r, + i; bool command_success = false; bool shutdown_success = false; - XLogRecPtr remote_last_checkpoint_lsn = InvalidXLogRecPtr; - ReplInfo replication_info = T_REPLINFO_INTIALIZER; + XLogRecPtr remote_last_checkpoint_lsn = InvalidXLogRecPtr; + ReplInfo replication_info = T_REPLINFO_INTIALIZER; /* store list of configuration files on the demotion candidate */ - KeyValueList remote_config_files = { NULL, NULL }; + KeyValueList remote_config_files = {NULL, NULL}; /* store list of sibling nodes if --siblings-follow specified */ NodeInfoList sibling_nodes = T_NODE_INFO_LIST_INITIALIZER; - int unreachable_sibling_node_count = 0; + int unreachable_sibling_node_count = 0; /* * SANITY CHECKS * - * We'll be doing a bunch of operations on the remote server (primary - * to be demoted) - careful checks needed before proceding. + * We'll be doing a bunch of operations on the remote server (primary to + * be demoted) - careful checks needed before proceding. */ local_conn = establish_db_connection(config_file_options.conninfo, true); @@ -2048,10 +2068,9 @@ do_standby_switchover(void) } /* - * Check this standby is attached to the demotion candidate - * TODO: - * - check standby is attached to demotion candidate - * - check application_name in pg_stat_replication + * Check this standby is attached to the demotion candidate TODO: - check + * standby is attached to demotion candidate - check application_name in + * pg_stat_replication */ if (local_node_record.upstream_node_id != remote_node_record.node_id) @@ -2070,8 +2089,9 @@ do_standby_switchover(void) /* - * If --force-rewind specified, check pg_rewind can be used, and pre-emptively - * fetch the list of configuration files which should be archived + * If --force-rewind specified, check pg_rewind can be used, and + * pre-emptively fetch the list of configuration files which should be + * archived */ if (runtime_options.force_rewind == true) @@ -2130,6 +2150,7 @@ do_standby_switchover(void) else { PQExpBufferData msg; + initPQExpBuffer(&msg); appendPQExpBuffer(&msg, @@ -2155,10 +2176,10 @@ do_standby_switchover(void) appendPQExpBuffer(&remote_command_str, "--version 2>/dev/null && echo \"1\" || echo \"0\""); initPQExpBuffer(&command_output); command_success = remote_command( - remote_host, - runtime_options.remote_user, - remote_command_str.data, - &command_output); + remote_host, + runtime_options.remote_user, + remote_command_str.data, + &command_output); termPQExpBuffer(&remote_command_str); @@ -2176,20 +2197,20 @@ do_standby_switchover(void) initPQExpBuffer(&hint); appendPQExpBuffer( - &hint, - _("check \"pg_bindir\" is set to the correct path in \"repmgr.conf\"; current value: ")); + &hint, + _("check \"pg_bindir\" is set to the correct path in \"repmgr.conf\"; current value: ")); if (strlen(config_file_options.pg_bindir)) { appendPQExpBuffer( - &hint, - "\"%s\"", config_file_options.pg_bindir); + &hint, + "\"%s\"", config_file_options.pg_bindir); } else { appendPQExpBuffer( - &hint, - "(not set)"); + &hint, + "(not set)"); } @@ -2211,15 +2232,15 @@ do_standby_switchover(void) /* check archive/replication status */ { - int lag_seconds = 0; + int lag_seconds = 0; CheckStatus status = CHECK_STATUS_UNKNOWN; /* archive status - check when "archive_mode" is activated */ if (guc_set(remote_conn, "archive_mode", "!=", "off")) { - int files = 0; - int threshold = 0; + int files = 0; + int threshold = 0; initPQExpBuffer(&remote_command_str); make_remote_repmgr_path(&remote_command_str, &remote_node_record); @@ -2229,10 +2250,10 @@ do_standby_switchover(void) initPQExpBuffer(&command_output); command_success = remote_command( - remote_host, - runtime_options.remote_user, - remote_command_str.data, - &command_output); + remote_host, + runtime_options.remote_user, + remote_command_str.data, + &command_output); termPQExpBuffer(&remote_command_str); @@ -2248,83 +2269,84 @@ do_standby_switchover(void) switch (status) { case CHECK_STATUS_UNKNOWN: - { - if (runtime_options.force == false) { - log_error(_("unable to check number of pending archive files on demotion candidate \"%s\""), - remote_node_record.node_name); - log_hint(_("use -F/--force to continue anyway")); - PQfinish(remote_conn); - PQfinish(local_conn); + if (runtime_options.force == false) + { + log_error(_("unable to check number of pending archive files on demotion candidate \"%s\""), + remote_node_record.node_name); + log_hint(_("use -F/--force to continue anyway")); + PQfinish(remote_conn); + PQfinish(local_conn); - exit(ERR_SWITCHOVER_FAIL); + exit(ERR_SWITCHOVER_FAIL); + } + + log_warning(_("unable to check number of pending archive files on demotion candidate \"%s\""), + remote_node_record.node_name); + log_notice(_("-F/--force set, continuing with switchover")); } - - log_warning(_("unable to check number of pending archive files on demotion candidate \"%s\""), - remote_node_record.node_name); - log_notice(_("-F/--force set, continuing with switchover")); - } - break; + break; case CHECK_STATUS_CRITICAL: - { - if (runtime_options.force == false) { - log_error(_("number of pending archive files on demotion candidate \"%s\" is critical"), - remote_node_record.node_name); + if (runtime_options.force == false) + { + log_error(_("number of pending archive files on demotion candidate \"%s\" is critical"), + remote_node_record.node_name); + log_detail(_("%i pending archive files (critical threshold: %i)"), + files, threshold); + log_hint(_("PostgreSQL will not shut down until all files are archived; use -F/--force to continue anyway")); + PQfinish(remote_conn); + PQfinish(local_conn); + + exit(ERR_SWITCHOVER_FAIL); + } + + log_warning(_("number of pending archive files on demotion candidate \"%s\" is critical"), + remote_node_record.node_name); log_detail(_("%i pending archive files (critical threshold: %i)"), files, threshold); - log_hint(_("PostgreSQL will not shut down until all files are archived; use -F/--force to continue anyway")); - PQfinish(remote_conn); - PQfinish(local_conn); - - exit(ERR_SWITCHOVER_FAIL); + log_notice(_("-F/--force set, continuing with switchover")); } - - log_warning(_("number of pending archive files on demotion candidate \"%s\" is critical"), - remote_node_record.node_name); - log_detail(_("%i pending archive files (critical threshold: %i)"), - files, threshold); - log_notice(_("-F/--force set, continuing with switchover")); - } - break; + break; case CHECK_STATUS_WARNING: - { - log_warning(_("number of pending archive files on demotion candidate \"%s\" is warning"), - remote_node_record.node_name); - log_detail(_("%i pending archive files (warning threshold: %i)"), - files, threshold); - log_hint(_("PostgreSQL will not shut down until all files are archived")); - } - break; + { + log_warning(_("number of pending archive files on demotion candidate \"%s\" is warning"), + remote_node_record.node_name); + log_detail(_("%i pending archive files (warning threshold: %i)"), + files, threshold); + log_hint(_("PostgreSQL will not shut down until all files are archived")); + } + break; case CHECK_STATUS_OK: - { - PQExpBufferData msg; - initPQExpBuffer(&msg); - - appendPQExpBuffer(&msg, - _("%i pending archive files"), - files); - - if (runtime_options.dry_run == true) { - log_info("%s", msg.data); - } - else - { - log_verbose(LOG_INFO, "%s", msg.data); - } + PQExpBufferData msg; - termPQExpBuffer(&msg); - } + initPQExpBuffer(&msg); + + appendPQExpBuffer(&msg, + _("%i pending archive files"), + files); + + if (runtime_options.dry_run == true) + { + log_info("%s", msg.data); + } + else + { + log_verbose(LOG_INFO, "%s", msg.data); + } + + termPQExpBuffer(&msg); + } } } else { - char *msg = _("archive mode is \"off\""); + char *msg = _("archive mode is \"off\""); if (runtime_options.dry_run == true) { @@ -2337,8 +2359,8 @@ do_standby_switchover(void) } /* - * check replication lag on promotion candidate - * (TODO: check on all nodes attached to demotion candidate) + * check replication lag on promotion candidate (TODO: check on all + * nodes attached to demotion candidate) */ lag_seconds = get_replication_lag_seconds(local_conn); @@ -2388,6 +2410,7 @@ do_standby_switchover(void) else { PQExpBufferData msg; + initPQExpBuffer(&msg); appendPQExpBuffer(&msg, @@ -2429,7 +2452,7 @@ do_standby_switchover(void) } else { - char host[MAXLEN] = ""; + char host[MAXLEN] = ""; NodeInfoListCell *cell; log_verbose(LOG_INFO, _("%i active sibling nodes found"), @@ -2493,7 +2516,7 @@ do_standby_switchover(void) } else { - char *msg = _("all sibling nodes are reachable via SSH"); + char *msg = _("all sibling nodes are reachable via SSH"); if (runtime_options.dry_run == true) { @@ -2506,7 +2529,7 @@ do_standby_switchover(void) } } } - //PQfinish(local_conn); + /* PQfinish(local_conn); */ /* @@ -2523,9 +2546,9 @@ do_standby_switchover(void) /* * Stop the remote primary * - * We'll issue the pg_ctl command but not force it not to wait; we'll check - * the connection from here - and error out if no shutdown is detected - * after a certain time. + * We'll issue the pg_ctl command but not force it not to wait; we'll + * check the connection from here - and error out if no shutdown is + * detected after a certain time. */ initPQExpBuffer(&remote_command_str); @@ -2548,23 +2571,24 @@ do_standby_switchover(void) "node service --action=stop --checkpoint"); } - // XXX handle failure + /* XXX handle failure */ - (void)remote_command( - remote_host, - runtime_options.remote_user, - remote_command_str.data, - &command_output); + (void) remote_command( + remote_host, + runtime_options.remote_user, + remote_command_str.data, + &command_output); termPQExpBuffer(&remote_command_str); /* - * --dry-run ends here with display of command which would be used to - * shut down the remote server + * --dry-run ends here with display of command which would be used to shut + * down the remote server */ if (runtime_options.dry_run == true) { - char shutdown_command[MAXLEN] = ""; + char shutdown_command[MAXLEN] = ""; + strncpy(shutdown_command, command_output.data, MAXLEN); termPQExpBuffer(&command_output); @@ -2589,7 +2613,7 @@ do_standby_switchover(void) for (i = 0; i < config_file_options.reconnect_attempts; i++) { /* Check whether primary is available */ - PGPing ping_res; + PGPing ping_res; log_info(_("checking primary status; %i of %i attempts"), i + 1, config_file_options.reconnect_attempts); @@ -2599,13 +2623,13 @@ do_standby_switchover(void) /* database server could not be contacted */ if (ping_res == PQPING_NO_RESPONSE || ping_res == PQPING_NO_ATTEMPT) { - bool command_success; + bool command_success; /* * remote server can't be contacted at protocol level - that - * doesn't necessarily mean it's shut down, so we'll ask - * its repmgr to check at data directory level, and if shut down - * also return the last checkpoint LSN. + * doesn't necessarily mean it's shut down, so we'll ask its + * repmgr to check at data directory level, and if shut down also + * return the last checkpoint LSN. */ initPQExpBuffer(&remote_command_str); @@ -2616,16 +2640,16 @@ do_standby_switchover(void) initPQExpBuffer(&command_output); command_success = remote_command( - remote_host, - runtime_options.remote_user, - remote_command_str.data, - &command_output); + remote_host, + runtime_options.remote_user, + remote_command_str.data, + &command_output); termPQExpBuffer(&remote_command_str); if (command_success == true) { - NodeStatus status = parse_node_status_is_shutdown_cleanly(command_output.data, &remote_last_checkpoint_lsn); + NodeStatus status = parse_node_status_is_shutdown_cleanly(command_output.data, &remote_last_checkpoint_lsn); if (status == NODE_STATUS_DOWN && remote_last_checkpoint_lsn != InvalidXLogRecPtr) { @@ -2690,15 +2714,15 @@ do_standby_switchover(void) _do_standby_promote_internal(local_conn, config_file_options.data_directory); /* - * Execute `repmgr node rejoin` to create recovery.conf and start - * the remote server. Additionally execute "pg_rewind", if required - * and requested. + * Execute `repmgr node rejoin` to create recovery.conf and start the + * remote server. Additionally execute "pg_rewind", if required and + * requested. */ initPQExpBuffer(&node_rejoin_options); if (replication_info.last_wal_receive_lsn < remote_last_checkpoint_lsn) { KeyValueListCell *cell = NULL; - bool first_entry = true; + bool first_entry = true; if (runtime_options.force_rewind == false) { @@ -2742,10 +2766,10 @@ do_standby_switchover(void) initPQExpBuffer(&command_output); command_success = remote_command( - remote_host, - runtime_options.remote_user, - remote_command_str.data, - &command_output); + remote_host, + runtime_options.remote_user, + remote_command_str.data, + &command_output); termPQExpBuffer(&remote_command_str); @@ -2780,12 +2804,12 @@ do_standby_switchover(void) /* clean up remote node */ remote_conn = establish_db_connection(remote_node_record.conninfo, false); - // check replication status + /* check replication status */ if (PQstatus(remote_conn) != CONNECTION_OK) { log_error(_("unable to reestablish connection to remote node \"%s\""), remote_node_record.node_name); - //log_hint(_("")); // depends on replication status + /* log_hint(_("")); // depends on replication status */ } else { @@ -2795,7 +2819,7 @@ do_standby_switchover(void) remote_node_record.node_id, local_node_record.slot_name); } - /* TODO warn about any inactive replication slots*/ + /* TODO warn about any inactive replication slots */ } PQfinish(remote_conn); @@ -2805,14 +2829,14 @@ do_standby_switchover(void) local_node_record.node_name); /* - * If --siblings-follow specified, attempt to make them follow the - * new standby + * If --siblings-follow specified, attempt to make them follow the new + * standby */ if (runtime_options.siblings_follow == true && sibling_nodes.node_count > 0) { - int failed_follow_count = 0; - char host[MAXLEN] = ""; + int failed_follow_count = 0; + char host[MAXLEN] = ""; NodeInfoListCell *cell = NULL; log_notice(_("executing STANDBY FOLLOW on %i of %i siblings"), @@ -2821,7 +2845,7 @@ do_standby_switchover(void) for (cell = sibling_nodes.head; cell; cell = cell->next) { - bool success = false; + bool success = false; t_node_info sibling_node_record = T_NODE_INFO_INITIALIZER; /* skip nodes previously determined as unreachable */ @@ -2843,10 +2867,10 @@ do_standby_switchover(void) initPQExpBuffer(&command_output); success = remote_command( - host, - runtime_options.remote_user, - remote_command_str.data, - &command_output); + host, + runtime_options.remote_user, + remote_command_str.data, + &command_output); termPQExpBuffer(&remote_command_str); @@ -2870,8 +2894,9 @@ do_standby_switchover(void) failed_follow_count); } - /* TODO: double-check all expected nodes are in pg_stat_replication and - * entries in repmgr.nodes match + /* + * TODO: double-check all expected nodes are in pg_stat_replication + * and entries in repmgr.nodes match */ } @@ -2888,13 +2913,13 @@ do_standby_switchover(void) static void check_source_server() { - PGconn *superuser_conn = NULL; - PGconn *privileged_conn = NULL; + PGconn *superuser_conn = NULL; + PGconn *privileged_conn = NULL; - char cluster_size[MAXLEN]; - t_node_info node_record = T_NODE_INFO_INITIALIZER; - RecordStatus record_status = RECORD_NOT_FOUND; - ExtensionStatus extension_status = REPMGR_UNKNOWN; + char cluster_size[MAXLEN]; + t_node_info node_record = T_NODE_INFO_INITIALIZER; + RecordStatus record_status = RECORD_NOT_FOUND; + ExtensionStatus extension_status = REPMGR_UNKNOWN; /* Attempt to connect to the upstream server to verify its configuration */ log_verbose(LOG_DEBUG, "check_source_server()"); @@ -2904,7 +2929,8 @@ check_source_server() /* * Unless in barman mode, exit with an error; - * establish_db_connection_by_params() will have already logged an error message + * establish_db_connection_by_params() will have already logged an error + * message */ if (PQstatus(source_conn) != CONNECTION_OK) { @@ -2930,8 +2956,8 @@ check_source_server() cluster_size); /* - * If the upstream node is a standby, try to connect to the primary too so we - * can write an event record + * If the upstream node is a standby, try to connect to the primary too so + * we can write an event record */ if (get_recovery_type(source_conn) == RECTYPE_STANDBY) { @@ -2950,8 +2976,8 @@ check_source_server() /* * Sanity-check that the primary node has a repmgr extension - if not - * present, fail with an error unless -F/--force is used (to enable - * repmgr to be used as a standalone clone tool) + * present, fail with an error unless -F/--force is used (to enable repmgr + * to be used as a standalone clone tool) */ extension_status = get_repmgr_extension_status(primary_conn); @@ -2999,13 +3025,13 @@ check_source_server() PQfinish(source_conn); source_conn = NULL; - if(superuser_conn != NULL) + if (superuser_conn != NULL) PQfinish(superuser_conn); exit(ERR_BAD_CONFIG); } - if(superuser_conn != NULL) + if (superuser_conn != NULL) PQfinish(superuser_conn); /* @@ -3079,29 +3105,32 @@ check_source_server() static void check_source_server_via_barman() { - char buf[MAXLEN] = ""; - char barman_conninfo_str[MAXLEN] = ""; + char buf[MAXLEN] = ""; + char barman_conninfo_str[MAXLEN] = ""; t_conninfo_param_list barman_conninfo = T_CONNINFO_PARAM_LIST_INITIALIZER; - char *errmsg = NULL; - bool parse_success = false, - command_success = false; - char where_condition[MAXLEN]; + char *errmsg = NULL; + bool parse_success = false, + command_success = false; + char where_condition[MAXLEN]; PQExpBufferData command_output; PQExpBufferData repmgr_conninfo_buf; - int c = 0; + int c = 0; get_barman_property(barman_conninfo_str, "conninfo", local_repmgr_tmp_directory); initialize_conninfo_params(&barman_conninfo, false); - /* parse_conninfo_string() here will remove the upstream's `application_name`, if set */ + /* + * parse_conninfo_string() here will remove the upstream's + * `application_name`, if set + */ parse_success = parse_conninfo_string(barman_conninfo_str, &barman_conninfo, errmsg, true); if (parse_success == false) { log_error(_("Unable to parse barman conninfo string \"%s\":\n%s"), - barman_conninfo_str, errmsg); + barman_conninfo_str, errmsg); exit(ERR_BARMAN); } @@ -3126,7 +3155,7 @@ check_source_server_via_barman() "repmgr database conninfo string on barman server: %s", repmgr_conninfo_buf.data); - // XXX check this works in all cases + /* XXX check this works in all cases */ maxlen_snprintf(where_condition, "node_id=%i", upstream_node_id); initPQExpBuffer(&command_output); @@ -3179,9 +3208,9 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in int i; bool config_ok = true; char *wal_error_message = NULL; - t_basebackup_options backup_options = T_BASEBACKUP_OPTIONS_INITIALIZER; + t_basebackup_options backup_options = T_BASEBACKUP_OPTIONS_INITIALIZER; bool backup_options_ok = true; - ItemList backup_option_errors = { NULL, NULL }; + ItemList backup_option_errors = {NULL, NULL}; bool xlog_stream = true; standy_clone_mode mode; @@ -3192,14 +3221,14 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in /* * Parse `pg_basebackup_options`, if set, to detect whether --xlog-method - * has been set to something other than `stream` (i.e. `fetch`), as - * this will influence some checks + * has been set to something other than `stream` (i.e. `fetch`), as this + * will influence some checks */ backup_options_ok = parse_pg_basebackup_options( - config_file_options.pg_basebackup_options, - &backup_options, server_version_num, - &backup_option_errors); + config_file_options.pg_basebackup_options, + &backup_options, server_version_num, + &backup_option_errors); if (backup_options_ok == false) { @@ -3220,33 +3249,34 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in /* Check that WAL level is set correctly */ { - char *levels_pre96[] = { + char *levels_pre96[] = { "hot_standby", "logical", NULL, }; /* - * Note that in 9.6+, "hot_standby" and "archive" are accepted as aliases - * for "replica", but current_setting() will of course always return "replica" + * Note that in 9.6+, "hot_standby" and "archive" are accepted as + * aliases for "replica", but current_setting() will of course always + * return "replica" */ - char *levels_96plus[] = { + char *levels_96plus[] = { "replica", "logical", NULL, }; - char **levels; - int j = 0; + char **levels; + int j = 0; if (server_version_num < 90600) { - levels = (char **)levels_pre96; + levels = (char **) levels_pre96; wal_error_message = _("parameter 'wal_level' must be set to 'hot_standby' or 'logical'"); } else { - levels = (char **)levels_96plus; + levels = (char **) levels_96plus; wal_error_message = _("parameter 'wal_level' must be set to 'replica' or 'logical'"); } @@ -3297,21 +3327,22 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in } } } + /* * physical replication slots not available or not requested - check if * there are any circumstances where `wal_keep_segments` should be set */ else if (mode != barman) { - bool check_wal_keep_segments = false; + bool check_wal_keep_segments = false; /* - * A non-zero `wal_keep_segments` value will almost certainly be required - * if pg_basebackup is being used with --xlog-method=fetch, + * A non-zero `wal_keep_segments` value will almost certainly be + * required if pg_basebackup is being used with --xlog-method=fetch, * *and* no restore command has been specified */ if (xlog_stream == false - && strcmp(config_file_options.restore_command, "") == 0) + && strcmp(config_file_options.restore_command, "") == 0) { check_wal_keep_segments = true; } @@ -3335,7 +3366,7 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in log_hint(_("In PostgreSQL 9.4 and later, replication slots can be used, which " "do not require \"wal_keep_segments\" to be set " "(set parameter \"use_replication_slots\" in repmgr.conf to enable)\n" - )); + )); } } @@ -3353,12 +3384,12 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in /* * If archive_mode is enabled, check that 'archive_command' is non empty - * (however it's not practical to check that it actually represents a valid - * command). + * (however it's not practical to check that it actually represents a + * valid command). * * From PostgreSQL 9.5, archive_mode can be one of 'off', 'on' or 'always' - * so for ease of backwards compatibility, rather than explicitly check for an - * enabled mode, check that it's not "off". + * so for ease of backwards compatibility, rather than explicitly check + * for an enabled mode, check that it's not "off". */ if (guc_set(conn, "archive_mode", "!=", "off")) @@ -3382,10 +3413,10 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in /* - * Check that 'hot_standby' is on. This isn't strictly necessary - * for the primary server, however the assumption is that we'll be - * cloning standbys and thus copying the primary configuration; - * this way the standby will be correctly configured by default. + * Check that 'hot_standby' is on. This isn't strictly necessary for the + * primary server, however the assumption is that we'll be cloning + * standbys and thus copying the primary configuration; this way the + * standby will be correctly configured by default. */ i = guc_set(conn, "hot_standby", "=", "on"); @@ -3424,9 +3455,9 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in } /* - * If using pg_basebackup, ensure sufficient replication connections can be made. - * There's no guarantee they'll still be available by the time pg_basebackup - * is executed, but there's nothing we can do about that. + * If using pg_basebackup, ensure sufficient replication connections can + * be made. There's no guarantee they'll still be available by the time + * pg_basebackup is executed, but there's nothing we can do about that. */ if (mode == pg_basebackup) { @@ -3438,7 +3469,10 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in t_conninfo_param_list repl_conninfo; - /* Make a copy of the connection parameter arrays, and append "replication" */ + /* + * Make a copy of the connection parameter arrays, and append + * "replication" + */ initialize_conninfo_params(&repl_conninfo, false); @@ -3467,10 +3501,13 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in connections = pg_malloc0(sizeof(PGconn *) * min_replication_connections); - /* Attempt to create the minimum number of required concurrent connections */ + /* + * Attempt to create the minimum number of required concurrent + * connections + */ for (i = 0; i < min_replication_connections; i++) { - PGconn *replication_conn; + PGconn *replication_conn; replication_conn = establish_db_connection_by_params(&repl_conninfo, false); @@ -3495,10 +3532,13 @@ check_upstream_config(PGconn *conn, int server_version_num, t_node_info *node_in config_ok = false; /* - * XXX at this point we could check current_setting('max_wal_senders) - COUNT(*) FROM pg_stat_replication; - * if >= min_replication_connections we could infer possible authentication error. + * XXX at this point we could check + * current_setting('max_wal_senders) - COUNT(*) FROM + * pg_stat_replication; if >= min_replication_connections we could + * infer possible authentication error. * - * Alternatively call PQconnectStart() and poll for presence/absence of CONNECTION_AUTH_OK ? + * Alternatively call PQconnectStart() and poll for + * presence/absence of CONNECTION_AUTH_OK ? */ log_error(_("unable to establish necessary replication connections")); log_hint(_("increase \"max_wal_senders\" by at least %i"), @@ -3533,8 +3573,8 @@ static void initialise_direct_clone(t_node_info *node_record) { /* - * Check the destination data directory can be used - * (in Barman mode, this directory will already have been created) + * Check the destination data directory can be used (in Barman mode, this + * directory will already have been created) */ if (!create_pg_dir(local_data_directory, runtime_options.force)) @@ -3549,44 +3589,45 @@ initialise_direct_clone(t_node_info *node_record) * Check that tablespaces named in any `tablespace_mapping` configuration * file parameters exist. * - * pg_basebackup doesn't verify mappings, so any errors will not be caught. - * We'll do that here as a value-added service. + * pg_basebackup doesn't verify mappings, so any errors will not be + * caught. We'll do that here as a value-added service. * */ if (config_file_options.tablespace_mapping.head != NULL) { TablespaceListCell *cell = false; - KeyValueList not_found = { NULL, NULL }; - int total = 0, matched = 0; - bool success = false; + KeyValueList not_found = {NULL, NULL}; + int total = 0, + matched = 0; + bool success = false; for (cell = config_file_options.tablespace_mapping.head; cell; cell = cell->next) { - char *old_dir_escaped = escape_string(source_conn, cell->old_dir); - char name[MAXLEN] = ""; + char *old_dir_escaped = escape_string(source_conn, cell->old_dir); + char name[MAXLEN] = ""; success = get_tablespace_name_by_location(source_conn, old_dir_escaped, name); pfree(old_dir_escaped); if (success == true) { - matched ++; + matched++; } else { key_value_list_set( - ¬_found, - cell->old_dir, - ""); + ¬_found, + cell->old_dir, + ""); } - total ++; + total++; } if (not_found.head != NULL) { - PQExpBufferData detail; + PQExpBufferData detail; KeyValueListCell *kv_cell; log_error(_("%i of %i mapped tablespaces not found"), @@ -3597,8 +3638,8 @@ initialise_direct_clone(t_node_info *node_record) for (kv_cell = not_found.head; kv_cell; kv_cell = kv_cell->next) { appendPQExpBuffer( - &detail, - " %s\n", kv_cell->key); + &detail, + " %s\n", kv_cell->key); } log_detail(_("following tablespaces not found:\n%s"), @@ -3610,23 +3651,24 @@ initialise_direct_clone(t_node_info *node_record) } /* - * If replication slots requested, create appropriate slot on the - * source node; this must be done before pg_basebackup is called. + * If replication slots requested, create appropriate slot on the source + * node; this must be done before pg_basebackup is called. * - * Note: if the source node is different to the specified upstream - * node, we'll need to drop the slot and recreate it on the upstream. + * Note: if the source node is different to the specified upstream node, + * we'll need to drop the slot and recreate it on the upstream. * * TODO: skip this for Pg10, and ensure temp slot option used * - * Replication slots are not supported (and not very useful - * anyway) in Barman mode. + * Replication slots are not supported (and not very useful anyway) in + * Barman mode. */ if (config_file_options.use_replication_slots == true) { - PGconn *superuser_conn = NULL; - PGconn *privileged_conn = NULL; + PGconn *superuser_conn = NULL; + PGconn *privileged_conn = NULL; PQExpBufferData event_details; + initPQExpBuffer(&event_details); get_superuser_connection(&source_conn, &superuser_conn, &privileged_conn); @@ -3636,12 +3678,12 @@ initialise_direct_clone(t_node_info *node_record) log_error("%s", event_details.data); create_event_notification( - primary_conn, - &config_file_options, - config_file_options.node_id, - "standby_clone", - false, - event_details.data); + primary_conn, + &config_file_options, + config_file_options.node_id, + "standby_clone", + false, + event_details.data); PQfinish(source_conn); @@ -3668,15 +3710,15 @@ initialise_direct_clone(t_node_info *node_record) static int run_basebackup(t_node_info *node_record) { - char script[MAXLEN] = ""; - int r = SUCCESS; - PQExpBufferData params; - TablespaceListCell *cell = NULL; - t_basebackup_options backup_options = T_BASEBACKUP_OPTIONS_INITIALIZER; + char script[MAXLEN] = ""; + int r = SUCCESS; + PQExpBufferData params; + TablespaceListCell *cell = NULL; + t_basebackup_options backup_options = T_BASEBACKUP_OPTIONS_INITIALIZER; /* - * Parse the pg_basebackup_options provided in repmgr.conf - we'll want - * to check later whether certain options were set by the user + * Parse the pg_basebackup_options provided in repmgr.conf - we'll want to + * check later whether certain options were set by the user */ parse_pg_basebackup_options(config_file_options.pg_basebackup_options, &backup_options, @@ -3692,13 +3734,13 @@ run_basebackup(t_node_info *node_record) /* * conninfo string provided - pass it to pg_basebackup as the -d option * (pg_basebackup doesn't require or want a database name, but for - * consistency with other applications accepts a conninfo string - * under -d/--dbname) + * consistency with other applications accepts a conninfo string under + * -d/--dbname) */ if (runtime_options.conninfo_provided == true) { t_conninfo_param_list conninfo = T_CONNINFO_PARAM_LIST_INITIALIZER; - char *conninfo_str = NULL; + char *conninfo_str = NULL; initialize_conninfo_params(&conninfo, false); @@ -3752,7 +3794,8 @@ run_basebackup(t_node_info *node_record) } - if (runtime_options.fast_checkpoint) { + if (runtime_options.fast_checkpoint) + { appendPQExpBuffer(¶ms, " -c fast"); } @@ -3765,13 +3808,13 @@ run_basebackup(t_node_info *node_record) } /* - * To ensure we have all the WALs needed during basebackup execution we stream - * them as the backup is taking place. + * To ensure we have all the WALs needed during basebackup execution we + * stream them as the backup is taking place. * * From 9.6, if replication slots are in use, we'll have previously - * created a slot with reserved LSN, and will stream from that slot to avoid - * WAL buildup on the primary using the -S/--slot, which requires -X/--xlog-method=stream - * (from 10, -X/--wal-method=stream) + * created a slot with reserved LSN, and will stream from that slot to + * avoid WAL buildup on the primary using the -S/--slot, which requires + * -X/--xlog-method=stream (from 10, -X/--wal-method=stream) */ if (!strlen(backup_options.xlog_method)) { @@ -3779,29 +3822,30 @@ run_basebackup(t_node_info *node_record) } /* - * From 9.6, pg_basebackup accepts -S/--slot, which forces WAL streaming to use - * the specified replication slot. If replication slot usage is specified, the - * slot will already have been created. + * From 9.6, pg_basebackup accepts -S/--slot, which forces WAL streaming + * to use the specified replication slot. If replication slot usage is + * specified, the slot will already have been created. * - * NOTE: currently there's no way of disabling the --slot option while using - * --xlog-method=stream - it's hard to imagine a use case for this, so no - * provision has been made for doing it. + * NOTE: currently there's no way of disabling the --slot option while + * using --xlog-method=stream - it's hard to imagine a use case for this, + * so no provision has been made for doing it. * - * NOTE: - * It's possible to set 'pg_basebackup_options' with an invalid combination - * of values for --wal-method (--xlog-method) and --slot - we're not checking that, just that - * we're not overriding any user-supplied values + * NOTE: It's possible to set 'pg_basebackup_options' with an invalid + * combination of values for --wal-method (--xlog-method) and --slot - + * we're not checking that, just that we're not overriding any + * user-supplied values */ if (source_server_version_num >= 90600 && config_file_options.use_replication_slots) { - bool slot_add = true; + bool slot_add = true; /* - * Check whether 'pg_basebackup_options' in repmgr.conf has the --slot option set, - * or if --wal-method (--xlog-method) is set to a value other than "stream" - * (in which case we can't use --slot). + * Check whether 'pg_basebackup_options' in repmgr.conf has the --slot + * option set, or if --wal-method (--xlog-method) is set to a value + * other than "stream" (in which case we can't use --slot). */ - if (strlen(backup_options.slot) || (strlen(backup_options.xlog_method) && strcmp(backup_options.xlog_method, "stream") != 0)) { + if (strlen(backup_options.slot) || (strlen(backup_options.xlog_method) && strcmp(backup_options.xlog_method, "stream") != 0)) + { slot_add = false; } @@ -3831,25 +3875,27 @@ run_basebackup(t_node_info *node_record) return ERR_BAD_BASEBACKUP; /* - * If replication slots in use, check the created slot is on the correct node; - * the slot will initially get created on the source node, and will need to be - * dropped and recreated on the actual upstream node if these differ. + * If replication slots in use, check the created slot is on the correct + * node; the slot will initially get created on the source node, and will + * need to be dropped and recreated on the actual upstream node if these + * differ. */ if (config_file_options.use_replication_slots && upstream_node_id != UNKNOWN_NODE_ID) { - PGconn *superuser_conn = NULL; - PGconn *privileged_conn = NULL; + PGconn *superuser_conn = NULL; + PGconn *privileged_conn = NULL; - t_node_info upstream_node_record = T_NODE_INFO_INITIALIZER; - t_replication_slot slot_info = T_REPLICATION_SLOT_INITIALIZER; - RecordStatus record_status = RECORD_NOT_FOUND; + t_node_info upstream_node_record = T_NODE_INFO_INITIALIZER; + t_replication_slot slot_info = T_REPLICATION_SLOT_INITIALIZER; + RecordStatus record_status = RECORD_NOT_FOUND; record_status = get_node_record(source_conn, upstream_node_id, &upstream_node_record); /* - * if there's no upstream record, there's no point in trying to create a replication - * slot on the designated upstream, as the assumption is it won't exist at this point. + * if there's no upstream record, there's no point in trying to create + * a replication slot on the designated upstream, as the assumption is + * it won't exist at this point. */ if (record_status != RECORD_FOUND) { @@ -3860,7 +3906,7 @@ run_basebackup(t_node_info *node_record) } else { - PGconn *upstream_conn = NULL; + PGconn *upstream_conn = NULL; upstream_conn = establish_db_connection(upstream_node_record.conninfo, true); @@ -3891,12 +3937,12 @@ run_basebackup(t_node_info *node_record) log_error("%s", event_details.data); create_event_notification( - primary_conn, - &config_file_options, - config_file_options.node_id, - "standby_clone", - false, - event_details.data); + primary_conn, + &config_file_options, + config_file_options.node_id, + "standby_clone", + false, + event_details.data); PQfinish(source_conn); @@ -3928,7 +3974,11 @@ run_basebackup(t_node_info *node_record) log_error(_("unable to delete replication slot \"%s\" on source node"), node_record->slot_name); } } - /* if replication slot is still active (shouldn't happen), emit a warning*/ + + /* + * if replication slot is still active (shouldn't happen), emit a + * warning + */ else { log_warning(_("replication slot \"%s\" is still active on source node"), node_record->slot_name); @@ -3947,15 +3997,17 @@ run_basebackup(t_node_info *node_record) static int run_file_backup(t_node_info *node_record) { - int r = SUCCESS, i; + int r = SUCCESS, + i; char command[MAXLEN] = ""; char filename[MAXLEN] = ""; char buf[MAXLEN] = ""; char basebackups_directory[MAXLEN] = ""; char backup_id[MAXLEN] = ""; - char *p = NULL, *q = NULL; - TablespaceDataList tablespace_list = { NULL, NULL }; + char *p = NULL, + *q = NULL; + TablespaceDataList tablespace_list = {NULL, NULL}; TablespaceDataListCell *cell_t = NULL; PQExpBufferData tablespace_map; @@ -3970,21 +4022,18 @@ run_file_backup(t_node_info *node_record) get_barman_property(basebackups_directory, "basebackups_directory", local_repmgr_tmp_directory); /* - * Read the list of backup files into a local file. In the - * process: + * Read the list of backup files into a local file. In the process: * - * - determine the backup ID; - * - check, and remove, the prefix; - * - detect tablespaces; - * - filter files in one list per tablespace; + * - determine the backup ID; - check, and remove, the prefix; - + * detect tablespaces; - filter files in one list per tablespace; */ { - FILE *fi; /* input stream */ - FILE *fd; /* output for data.txt */ - char prefix[MAXLEN] = ""; - char output[MAXLEN] = ""; - int n = 0; + FILE *fi; /* input stream */ + FILE *fd; /* output for data.txt */ + char prefix[MAXLEN] = ""; + char output[MAXLEN] = ""; + int n = 0; maxlen_snprintf(command, "%s list-files --target=data %s latest", make_barman_ssh_command(barman_command_buf), @@ -4017,23 +4066,23 @@ run_file_backup(t_node_info *node_record) if (p == NULL) { log_error("unexpected output from \"barman list-files\": %s", - output); + output); exit(ERR_BARMAN); } /* * Remove and note backup ID; copy backup.info */ - if (! strcmp(backup_id, "")) + if (!strcmp(backup_id, "")) { - FILE *fi2; + FILE *fi2; n = strcspn(p, "/"); strncpy(backup_id, p, n); - strncat(prefix,backup_id,MAXLEN-1); - strncat(prefix,"/",MAXLEN-1); + strncat(prefix, backup_id, MAXLEN - 1); + strncat(prefix, "/", MAXLEN - 1); p = string_skip_prefix(backup_id, p); p = string_skip_prefix("/", p); @@ -4046,9 +4095,9 @@ run_file_backup(t_node_info *node_record) basebackups_directory, backup_id, local_repmgr_tmp_directory); - (void)local_command( - command, - NULL); + (void) local_command( + command, + NULL); /* * Get tablespace data @@ -4130,19 +4179,18 @@ run_file_backup(t_node_info *node_record) } /* - * As of Barman version 1.6.1, the file structure of a backup - * is as follows: + * As of Barman version 1.6.1, the file structure of a backup is as + * follows: * - * base/ - base backup - * wals/ - WAL files associated to the backup + * base/ - base backup wals/ - WAL files associated to the backup * * base/ - backup files * - * here ID has the standard timestamp form yyyymmddThhmmss + * here ID has the standard timestamp form yyyymmddThhmmss * * base//backup.info - backup metadata, in text format - * base//data - data directory - * base// - tablespace with the given oid + * base//data - data directory base// - + * tablespace with the given oid */ /* @@ -4156,21 +4204,22 @@ run_file_backup(t_node_info *node_record) backup_id, local_data_directory); - (void)local_command( - command, - NULL); + (void) local_command( + command, + NULL); unlink(datadir_list_filename); /* - * We must create some PGDATA subdirectories because they are - * not included in the Barman backup. + * We must create some PGDATA subdirectories because they are not + * included in the Barman backup. * - * See class RsyncBackupExecutor in the Barman source (barman/backup_executor.py) - * for a definitive list of excluded directories. + * See class RsyncBackupExecutor in the Barman source + * (barman/backup_executor.py) for a definitive list of excluded + * directories. */ { - const char* const dirs[] = { + const char *const dirs[] = { /* Only from 10 */ "pg_wal", /* Only from 9.5 */ @@ -4181,20 +4230,24 @@ run_file_backup(t_node_info *node_record) "pg_notify", "pg_serial", "pg_snapshots", "pg_stat", "pg_stat_tmp", "pg_tblspc", "pg_twophase", "pg_xlog", 0 }; - const int vers[] = { + const int vers[] = { 100000, 90500, 90400, 90400, 90400, 90400, 90400, 0, 0, 0, 0, 0, 0, 0, -100000, 0 }; + for (i = 0; dirs[i]; i++) { /* directory exists in newer versions than this server - skip */ if (vers[i] > 0 && source_server_version_num < vers[i]) continue; - /* directory existed in earlier versions than this server but has been removed/renamed - skip */ + /* + * directory existed in earlier versions than this server but + * has been removed/renamed - skip + */ if (vers[i] < 0 && source_server_version_num >= abs(vers[i])) continue; @@ -4211,11 +4264,14 @@ run_file_backup(t_node_info *node_record) for (cell_t = tablespace_list.head; cell_t; cell_t = cell_t->next) { - bool mapping_found = false; + bool mapping_found = false; TablespaceListCell *cell = NULL; - char *tblspc_dir_dest = NULL; + char *tblspc_dir_dest = NULL; - /* Check if tablespace path matches one of the provided tablespace mappings */ + /* + * Check if tablespace path matches one of the provided tablespace + * mappings + */ if (config_file_options.tablespace_mapping.head != NULL) { for (cell = config_file_options.tablespace_mapping.head; cell; cell = cell->next) @@ -4247,7 +4303,8 @@ run_file_backup(t_node_info *node_record) { create_pg_dir(cell_t->location, false); - if (cell_t->f != NULL) /* cell_t->f == NULL iff the tablespace is empty */ + if (cell_t->f != NULL) /* cell_t->f == NULL iff the tablespace is + * empty */ { maxlen_snprintf(command, "rsync --progress -a --files-from=%s/%s.txt %s:%s/base/%s/%s %s", @@ -4258,9 +4315,9 @@ run_file_backup(t_node_info *node_record) backup_id, cell_t->oid, tblspc_dir_dest); - (void)local_command( - command, - NULL); + (void) local_command( + command, + NULL); fclose(cell_t->f); maxlen_snprintf(filename, "%s/%s.txt", @@ -4272,10 +4329,9 @@ run_file_backup(t_node_info *node_record) /* - * If a valid mapping was provide for this tablespace, arrange for it to - * be remapped - * (if no tablespace mapping was provided, the link will be copied as-is - * by pg_basebackup and no action is required) + * If a valid mapping was provide for this tablespace, arrange for it + * to be remapped (if no tablespace mapping was provided, the link + * will be copied as-is by pg_basebackup and no action is required) */ if (mapping_found == true || mode == barman) { @@ -4288,7 +4344,11 @@ run_file_backup(t_node_info *node_record) cell_t->oid, tblspc_dir_dest); } - /* Pre-9.5, we have to manipulate the symlinks in pg_tblspc/ ourselves */ + + /* + * Pre-9.5, we have to manipulate the symlinks in pg_tblspc/ + * ourselves + */ else { PQExpBufferData tblspc_symlink; @@ -4318,23 +4378,27 @@ run_file_backup(t_node_info *node_record) } /* - * For 9.5 and later, if tablespace remapping was requested, we'll need - * to rewrite the tablespace map file ourselves. - * The tablespace map file is read on startup and any links created by - * the backend; we could do this ourselves like for pre-9.5 servers, but - * it's better to rely on functionality the backend provides. + * For 9.5 and later, if tablespace remapping was requested, we'll need to + * rewrite the tablespace map file ourselves. The tablespace map file is + * read on startup and any links created by the backend; we could do this + * ourselves like for pre-9.5 servers, but it's better to rely on + * functionality the backend provides. */ if (source_server_version_num >= 90500 && tablespace_map_rewrite == true) { PQExpBufferData tablespace_map_filename; FILE *tablespace_map_file; + initPQExpBuffer(&tablespace_map_filename); appendPQExpBuffer(&tablespace_map_filename, "%s/%s", local_data_directory, TABLESPACE_MAP); - /* Unlink any existing file (it should be there, but we don't care if it isn't) */ + /* + * Unlink any existing file (it should be there, but we don't care if + * it isn't) + */ if (unlink(tablespace_map_filename.data) < 0 && errno != ENOENT) { log_error(_("unable to remove tablespace_map file %s: %s"), @@ -4358,7 +4422,7 @@ run_file_backup(t_node_info *node_record) { log_error(_("unable to write to tablespace_map file '%s'"), tablespace_map_filename.data); - r = ERR_BAD_BASEBACKUP; + r = ERR_BAD_BASEBACKUP; goto stop_backup; } @@ -4397,60 +4461,66 @@ make_barman_ssh_command(char *buf) static int -get_tablespace_data_barman -( char *tablespace_data_barman, - TablespaceDataList *tablespace_list) + get_tablespace_data_barman + (char *tablespace_data_barman, + TablespaceDataList *tablespace_list) { /* - * Example: - * [('main', 24674, '/var/lib/postgresql/tablespaces/9.5/main'), ('alt', 24678, '/var/lib/postgresql/tablespaces/9.5/alt')] + * Example: [('main', 24674, '/var/lib/postgresql/tablespaces/9.5/main'), + * ('alt', 24678, '/var/lib/postgresql/tablespaces/9.5/alt')] */ - char name[MAXLEN] = ""; - char oid[MAXLEN] = ""; - char location[MAXPGPATH] = ""; - char *p = tablespace_data_barman; - int i = 0; + char name[MAXLEN] = ""; + char oid[MAXLEN] = ""; + char location[MAXPGPATH] = ""; + char *p = tablespace_data_barman; + int i = 0; tablespace_list->head = NULL; tablespace_list->tail = NULL; p = string_skip_prefix("[", p); - if (p == NULL) return -1; + if (p == NULL) + return -1; while (*p == '(') { p = string_skip_prefix("('", p); - if (p == NULL) return -1; + if (p == NULL) + return -1; i = strcspn(p, "'"); strncpy(name, p, i); name[i] = 0; p = string_skip_prefix("', ", p + i); - if (p == NULL) return -1; + if (p == NULL) + return -1; i = strcspn(p, ","); strncpy(oid, p, i); oid[i] = 0; p = string_skip_prefix(", '", p + i); - if (p == NULL) return -1; + if (p == NULL) + return -1; i = strcspn(p, "'"); strncpy(location, p, i); location[i] = 0; p = string_skip_prefix("')", p + i); - if (p == NULL) return -1; + if (p == NULL) + return -1; - tablespace_data_append (tablespace_list, name, oid, location); + tablespace_data_append(tablespace_list, name, oid, location); if (*p == ']') break; p = string_skip_prefix(", ", p); - if (p == NULL) return -1; + if (p == NULL) + return -1; } return SUCCESS; @@ -4461,16 +4531,16 @@ void get_barman_property(char *dst, char *name, char *local_repmgr_directory) { PQExpBufferData command_output; - char buf[MAXLEN] = ""; - char command[MAXLEN] = ""; - char *p = NULL; + char buf[MAXLEN] = ""; + char command[MAXLEN] = ""; + char *p = NULL; initPQExpBuffer(&command_output); maxlen_snprintf(command, "grep \"^\t%s:\" %s/show-server.txt", name, local_repmgr_tmp_directory); - (void)local_command(command, &command_output); + (void) local_command(command, &command_output); maxlen_snprintf(buf, "\t%s: ", name); p = string_skip_prefix(buf, command_output.data); @@ -4491,9 +4561,10 @@ get_barman_property(char *dst, char *name, char *local_repmgr_directory) static void copy_configuration_files(void) { - int i, r; + int i, + r; t_configfile_info *file = NULL; - char *host = NULL; + char *host = NULL; /* get host from upstream record */ host = param_get(&recovery_conninfo, "host"); @@ -4505,12 +4576,13 @@ copy_configuration_files(void) for (i = 0; i < config_files.entries; i++) { - char dest_path[MAXPGPATH] = ""; + char dest_path[MAXPGPATH] = ""; + file = config_files.files[i]; /* - * Skip files in the data directory - these will be copied during - * the main backup + * Skip files in the data directory - these will be copied during the + * main backup */ if (file->in_data_directory == true) continue; @@ -4553,12 +4625,12 @@ tablespace_data_append(TablespaceDataList *list, const char *name, const char *o exit(ERR_OUT_OF_MEMORY); } - cell->oid = pg_malloc(1 + strlen(oid )); - cell->name = pg_malloc(1 + strlen(name )); + cell->oid = pg_malloc(1 + strlen(oid)); + cell->name = pg_malloc(1 + strlen(name)); cell->location = pg_malloc(1 + strlen(location)); - strncpy(cell->oid , oid , 1 + strlen(oid )); - strncpy(cell->name , name , 1 + strlen(name )); + strncpy(cell->oid, oid, 1 + strlen(oid)); + strncpy(cell->name, name, 1 + strlen(name)); strncpy(cell->location, location, 1 + strlen(location)); if (list->tail) @@ -4639,8 +4711,8 @@ check_recovery_type(PGconn *conn) static void drop_replication_slot_if_exists(PGconn *conn, int node_id, char *slot_name) { - t_replication_slot slot_info = T_REPLICATION_SLOT_INITIALIZER; - RecordStatus record_status = get_slot_record(conn, slot_name, &slot_info); + t_replication_slot slot_info = T_REPLICATION_SLOT_INITIALIZER; + RecordStatus record_status = get_slot_record(conn, slot_name, &slot_info); log_verbose(LOG_DEBUG, "attempting to delete slot \"%s\" on node %i", slot_name, node_id); @@ -4663,7 +4735,11 @@ drop_replication_slot_if_exists(PGconn *conn, int node_id, char *slot_name) log_error(_("unable to delete replication slot \"%s\" on node %i"), slot_name, node_id); } } - /* if active replication slot exists, call Houston as we have a problem */ + + /* + * if active replication slot exists, call Houston as we have a + * problem + */ else { log_warning(_("replication slot \"%s\" is still active on node %i"), slot_name, node_id); @@ -4676,21 +4752,22 @@ drop_replication_slot_if_exists(PGconn *conn, int node_id, char *slot_name) static NodeStatus parse_node_status_is_shutdown_cleanly(const char *node_status_output, XLogRecPtr *checkPoint) { - int options_len = 0; - char *options_string = NULL; - char *options_string_ptr = NULL; - NodeStatus node_status = NODE_STATUS_UNKNOWN; + int options_len = 0; + char *options_string = NULL; + char *options_string_ptr = NULL; + NodeStatus node_status = NODE_STATUS_UNKNOWN; /* - * Add parsed options to this list, then copy to an array - * to pass to getopt + * Add parsed options to this list, then copy to an array to pass to + * getopt */ - static ItemList option_argv = { NULL, NULL }; + static ItemList option_argv = {NULL, NULL}; - char *argv_item; - int c, argc_item = 1; + char *argv_item; + int c, + argc_item = 1; - char **argv_array; + char **argv_array; ItemListCell *cell; int optindex = 0; @@ -4730,8 +4807,8 @@ parse_node_status_is_shutdown_cleanly(const char *node_status_output, XLogRecPtr /* * Array of argument values to pass to getopt_long - this will need to - * include an empty string as the first value (normally this would be - * the program name) + * include an empty string as the first value (normally this would be the + * program name) */ argv_array = pg_malloc0(sizeof(char *) * (argc_item + 2)); @@ -4745,7 +4822,7 @@ parse_node_status_is_shutdown_cleanly(const char *node_status_output, XLogRecPtr */ for (cell = option_argv.head; cell; cell = cell->next) { - int argv_len = strlen(cell->string) + 1; + int argv_len = strlen(cell->string) + 1; argv_array[c] = pg_malloc0(argv_len); @@ -4767,39 +4844,40 @@ parse_node_status_is_shutdown_cleanly(const char *node_status_output, XLogRecPtr { switch (c) { - /* --last-checkpoint-lsn */ + /* --last-checkpoint-lsn */ case 'L': *checkPoint = parse_lsn(optarg); break; - /* --state */ + /* --state */ case 'S': - { - if (strncmp(optarg, "RUNNING", MAXLEN) == 0) { - node_status = NODE_STATUS_UP; + if (strncmp(optarg, "RUNNING", MAXLEN) == 0) + { + node_status = NODE_STATUS_UP; + } + else if (strncmp(optarg, "SHUTDOWN", MAXLEN) == 0) + { + node_status = NODE_STATUS_DOWN; + } + else if (strncmp(optarg, "UNCLEAN_SHUTDOWN", MAXLEN) == 0) + { + node_status = NODE_STATUS_UNCLEAN_SHUTDOWN; + } + else if (strncmp(optarg, "UNKNOWN", MAXLEN) == 0) + { + node_status = NODE_STATUS_UNKNOWN; + } } - else if (strncmp(optarg, "SHUTDOWN", MAXLEN) == 0) - { - node_status = NODE_STATUS_DOWN; - } - else if (strncmp(optarg, "UNCLEAN_SHUTDOWN", MAXLEN) == 0) - { - node_status = NODE_STATUS_UNCLEAN_SHUTDOWN; - } - else if (strncmp(optarg, "UNKNOWN", MAXLEN) == 0) - { - node_status = NODE_STATUS_UNKNOWN; - } - } - break; + break; } } pfree(options_string); { - int i; - for (i = 0; i < argc_item + 2; i ++) + int i; + + for (i = 0; i < argc_item + 2; i++) pfree(argv_array[i]); } pfree(argv_array); @@ -4812,23 +4890,24 @@ parse_node_status_is_shutdown_cleanly(const char *node_status_output, XLogRecPtr static CheckStatus parse_node_check_archiver(const char *node_check_output, int *files, int *threshold) { - int options_len = 0; - char *options_string = NULL; - char *options_string_ptr = NULL; + int options_len = 0; + char *options_string = NULL; + char *options_string_ptr = NULL; CheckStatus status = CHECK_STATUS_UNKNOWN; /* - * Add parsed options to this list, then copy to an array - * to pass to getopt + * Add parsed options to this list, then copy to an array to pass to + * getopt */ - static ItemList option_argv = { NULL, NULL }; + static ItemList option_argv = {NULL, NULL}; - char *argv_item; - int c, argc_item = 1; + char *argv_item; + int c, + argc_item = 1; - char **argv_array; + char **argv_array; ItemListCell *cell; int optindex = 0; @@ -4871,8 +4950,8 @@ parse_node_check_archiver(const char *node_check_output, int *files, int *thresh /* * Array of argument values to pass to getopt_long - this will need to - * include an empty string as the first value (normally this would be - * the program name) + * include an empty string as the first value (normally this would be the + * program name) */ argv_array = pg_malloc0(sizeof(char *) * (argc_item + 2)); @@ -4886,7 +4965,7 @@ parse_node_check_archiver(const char *node_check_output, int *files, int *thresh */ for (cell = option_argv.head; cell; cell = cell->next) { - int argv_len = strlen(cell->string) + 1; + int argv_len = strlen(cell->string) + 1; argv_array[c] = pg_malloc0(argv_len); @@ -4908,7 +4987,7 @@ parse_node_check_archiver(const char *node_check_output, int *files, int *thresh { switch (c) { - /* --files */ + /* --files */ case 'f': *files = atoi(optarg); break; @@ -4917,31 +4996,31 @@ parse_node_check_archiver(const char *node_check_output, int *files, int *thresh *threshold = atoi(optarg); break; - /* --status */ + /* --status */ case 'S': - { - if (strncmp(optarg, "OK", MAXLEN) == 0) { - status = CHECK_STATUS_OK; + if (strncmp(optarg, "OK", MAXLEN) == 0) + { + status = CHECK_STATUS_OK; + } + else if (strncmp(optarg, "WARNING", MAXLEN) == 0) + { + status = CHECK_STATUS_WARNING; + } + else if (strncmp(optarg, "CRITICAL", MAXLEN) == 0) + { + status = CHECK_STATUS_CRITICAL; + } + else if (strncmp(optarg, "UNKNOWN", MAXLEN) == 0) + { + status = CHECK_STATUS_UNKNOWN; + } + else + { + status = CHECK_STATUS_UNKNOWN; + } } - else if (strncmp(optarg, "WARNING", MAXLEN) == 0) - { - status = CHECK_STATUS_WARNING; - } - else if (strncmp(optarg, "CRITICAL", MAXLEN) == 0) - { - status = CHECK_STATUS_CRITICAL; - } - else if (strncmp(optarg, "UNKNOWN", MAXLEN) == 0) - { - status = CHECK_STATUS_UNKNOWN; - } - else - { - status = CHECK_STATUS_UNKNOWN; - } - } - break; + break; } } @@ -4953,23 +5032,24 @@ parse_node_check_archiver(const char *node_check_output, int *files, int *thresh static CheckStatus parse_node_check_replication_lag(const char *node_check_output, int *seconds, int *threshold) { - int options_len = 0; - char *options_string = NULL; - char *options_string_ptr = NULL; + int options_len = 0; + char *options_string = NULL; + char *options_string_ptr = NULL; CheckStatus status = CHECK_STATUS_UNKNOWN; /* - * Add parsed options to this list, then copy to an array - * to pass to getopt + * Add parsed options to this list, then copy to an array to pass to + * getopt */ - static ItemList option_argv = { NULL, NULL }; + static ItemList option_argv = {NULL, NULL}; - char *argv_item; - int c, argc_item = 1; + char *argv_item; + int c, + argc_item = 1; - char **argv_array; + char **argv_array; ItemListCell *cell; int optindex = 0; @@ -5012,8 +5092,8 @@ parse_node_check_replication_lag(const char *node_check_output, int *seconds, in /* * Array of argument values to pass to getopt_long - this will need to - * include an empty string as the first value (normally this would be - * the program name) + * include an empty string as the first value (normally this would be the + * program name) */ argv_array = pg_malloc0(sizeof(char *) * (argc_item + 2)); @@ -5027,7 +5107,7 @@ parse_node_check_replication_lag(const char *node_check_output, int *seconds, in */ for (cell = option_argv.head; cell; cell = cell->next) { - int argv_len = strlen(cell->string) + 1; + int argv_len = strlen(cell->string) + 1; argv_array[c] = pg_malloc0(argv_len); @@ -5049,7 +5129,7 @@ parse_node_check_replication_lag(const char *node_check_output, int *seconds, in { switch (c) { - /* --files */ + /* --files */ case 'l': *seconds = atoi(optarg); break; @@ -5058,31 +5138,31 @@ parse_node_check_replication_lag(const char *node_check_output, int *seconds, in *threshold = atoi(optarg); break; - /* --status */ + /* --status */ case 'S': - { - if (strncmp(optarg, "OK", MAXLEN) == 0) { - status = CHECK_STATUS_OK; + if (strncmp(optarg, "OK", MAXLEN) == 0) + { + status = CHECK_STATUS_OK; + } + else if (strncmp(optarg, "WARNING", MAXLEN) == 0) + { + status = CHECK_STATUS_WARNING; + } + else if (strncmp(optarg, "CRITICAL", MAXLEN) == 0) + { + status = CHECK_STATUS_CRITICAL; + } + else if (strncmp(optarg, "UNKNOWN", MAXLEN) == 0) + { + status = CHECK_STATUS_UNKNOWN; + } + else + { + status = CHECK_STATUS_UNKNOWN; + } } - else if (strncmp(optarg, "WARNING", MAXLEN) == 0) - { - status = CHECK_STATUS_WARNING; - } - else if (strncmp(optarg, "CRITICAL", MAXLEN) == 0) - { - status = CHECK_STATUS_CRITICAL; - } - else if (strncmp(optarg, "UNKNOWN", MAXLEN) == 0) - { - status = CHECK_STATUS_UNKNOWN; - } - else - { - status = CHECK_STATUS_UNKNOWN; - } - } - break; + break; } } @@ -5128,10 +5208,10 @@ do_standby_help(void) puts(""); printf(_(" \"standby register\" registers the standby node.\n")); puts(""); - printf(_(" -F, --force overwrite an existing node record, or if primary connection\n"\ + printf(_(" -F, --force overwrite an existing node record, or if primary connection\n" \ " parameters supplied, create record even if standby offline\n")); printf(_(" --upstream-node-id ID of the upstream node to replicate from (optional)\n")); - printf(_(" --wait-sync[=VALUE] wait for the node record to synchronise to the standby\n"\ + printf(_(" --wait-sync[=VALUE] wait for the node record to synchronise to the standby\n" \ " (optional timeout in seconds)\n")); puts(""); diff --git a/repmgr-action-standby.h b/repmgr-action-standby.h index 4ae1aaf0..9c4d62b1 100644 --- a/repmgr-action-standby.h +++ b/repmgr-action-standby.h @@ -32,4 +32,4 @@ extern bool do_standby_follow_internal(PGconn *primary_conn, t_node_info *primar -#endif /* _REPMGR_ACTION_STANDBY_H_ */ +#endif /* _REPMGR_ACTION_STANDBY_H_ */ diff --git a/repmgr-client-global.h b/repmgr-client-global.h index 935aef7a..17367ffa 100644 --- a/repmgr-client-global.h +++ b/repmgr-client-global.h @@ -40,11 +40,11 @@ typedef struct char config_file[MAXPGPATH]; bool dry_run; bool force; - char pg_bindir[MAXLEN]; /* overrides setting in repmgr.conf */ + char pg_bindir[MAXLEN]; /* overrides setting in repmgr.conf */ bool wait; /* logging options */ - char log_level[MAXLEN]; /* overrides setting in repmgr.conf */ + char log_level[MAXLEN]; /* overrides setting in repmgr.conf */ bool log_to_file; bool terse; bool verbose; @@ -119,7 +119,7 @@ typedef struct /* following options for internal use */ char config_archive_dir[MAXPGPATH]; OutputMode output_mode; -} t_runtime_options; +} t_runtime_options; #define T_RUNTIME_OPTIONS_INITIALIZER { \ /* configuration metadata */ \ @@ -160,12 +160,14 @@ typedef struct } -typedef enum { +typedef enum +{ barman, pg_basebackup -} standy_clone_mode; +} standy_clone_mode; -typedef enum { +typedef enum +{ ACTION_UNKNOWN = -1, ACTION_NONE, ACTION_START, @@ -184,21 +186,21 @@ extern t_configuration_options config_file_options; t_conninfo_param_list source_conninfo; -extern bool config_file_required; -extern char pg_bindir[MAXLEN]; +extern bool config_file_required; +extern char pg_bindir[MAXLEN]; extern t_node_info target_node_info; -extern int check_server_version(PGconn *conn, char *server_type, bool exit_on_error, char *server_version_string); +extern int check_server_version(PGconn *conn, char *server_type, bool exit_on_error, char *server_version_string); extern bool create_repmgr_extension(PGconn *conn); -extern int test_ssh_connection(char *host, char *remote_user); +extern int test_ssh_connection(char *host, char *remote_user); extern bool local_command(const char *command, PQExpBufferData *outputbuf); extern standy_clone_mode get_standby_clone_mode(void); -extern int copy_remote_files(char *host, char *remote_user, char *remote_path, - char *local_path, bool is_directory, int server_version_num); +extern int copy_remote_files(char *host, char *remote_user, char *remote_path, + char *local_path, bool is_directory, int server_version_num); extern void print_error_list(ItemList *error_list, int log_level); @@ -219,4 +221,4 @@ extern bool data_dir_required_for_action(t_server_action action); extern void get_node_data_directory(char *data_dir_buf); extern void init_node_record(t_node_info *node_record); -#endif /* _REPMGR_CLIENT_GLOBAL_H_ */ +#endif /* _REPMGR_CLIENT_GLOBAL_H_ */ diff --git a/repmgr-client.c b/repmgr-client.c index 45407e5e..0eddc7d2 100644 --- a/repmgr-client.c +++ b/repmgr-client.c @@ -61,7 +61,7 @@ #include "repmgr-action-cluster.h" -#include /* for PG_TEMP_FILE_PREFIX */ +#include /* for PG_TEMP_FILE_PREFIX */ /* globally available variables * @@ -73,10 +73,10 @@ t_configuration_options config_file_options = T_CONFIGURATION_OPTIONS_INITIALIZE /* conninfo params for the node we're operating on */ t_conninfo_param_list source_conninfo; -bool config_file_required = true; -char pg_bindir[MAXLEN] = ""; +bool config_file_required = true; +char pg_bindir[MAXLEN] = ""; -char path_buf[MAXLEN] = ""; +char path_buf[MAXLEN] = ""; /* * if --node-id/--node-name provided, place that node's record here @@ -86,8 +86,8 @@ t_node_info target_node_info = T_NODE_INFO_INITIALIZER; /* Collate command line errors and warnings here for friendlier reporting */ -static ItemList cli_errors = { NULL, NULL }; -static ItemList cli_warnings = { NULL, NULL }; +static ItemList cli_errors = {NULL, NULL}; +static ItemList cli_warnings = {NULL, NULL}; int @@ -104,14 +104,14 @@ main(int argc, char **argv) int action = NO_ACTION; char *dummy_action = ""; - bool help_option = false; + bool help_option = false; set_progname(argv[0]); /* - * Tell the logger we're a command-line program - this will - * ensure any output logged before the logger is initialized - * will be formatted correctly. Can be overriden with "--log-to-file". + * Tell the logger we're a command-line program - this will ensure any + * output logged before the logger is initialized will be formatted + * correctly. Can be overriden with "--log-to-file". */ logger_output_mode = OM_COMMAND_LINE; @@ -119,14 +119,13 @@ main(int argc, char **argv) * Initialize and pre-populate conninfo parameters; these will be * overwritten if matching command line parameters are provided. * - * Only some actions will need these, but we need to do this before - * the command line is parsed. + * Only some actions will need these, but we need to do this before the + * command line is parsed. * - * Note: PQconndefaults() does not provide a default value for - * "dbname", but if none is provided will default to "username" - * when the connection is made. We won't set "dbname" here if no - * default available, as that would break the libpq behaviour if - * non-default username is provided. + * Note: PQconndefaults() does not provide a default value for "dbname", + * but if none is provided will default to "username" when the connection + * is made. We won't set "dbname" here if no default available, as that + * would break the libpq behaviour if non-default username is provided. */ initialize_conninfo_params(&default_conninfo, true); @@ -138,7 +137,7 @@ main(int argc, char **argv) strncpy(runtime_options.host, default_conninfo.values[c], MAXLEN); } else if (strcmp(default_conninfo.keywords[c], "hostaddr") == 0 && - (default_conninfo.values[c] != NULL)) + (default_conninfo.values[c] != NULL)) { strncpy(runtime_options.host, default_conninfo.values[c], MAXLEN); } @@ -180,18 +179,18 @@ main(int argc, char **argv) &optindex)) != -1) { /* - * NOTE: some integer parameters (e.g. -p/--port) are stored internally - * as strings. We use repmgr_atoi() to check these but discard the - * returned integer; repmgr_atoi() will append the error message to the - * provided list. + * NOTE: some integer parameters (e.g. -p/--port) are stored + * internally as strings. We use repmgr_atoi() to check these but + * discard the returned integer; repmgr_atoi() will append the error + * message to the provided list. */ switch (c) { - /* - * Options which cause repmgr to exit in this block; - * these are the only ones which can be executed as root user - */ - case OPT_HELP: /* --help */ + /* + * Options which cause repmgr to exit in this block; these are + * the only ones which can be executed as root user + */ + case OPT_HELP: /* --help */ help_option = true; break; case '?': @@ -202,68 +201,74 @@ main(int argc, char **argv) } break; case 'V': + /* - * in contrast to repmgr3 and earlier, we only display the repmgr version - * as it's not specific to a particular PostgreSQL version + * in contrast to repmgr3 and earlier, we only display the + * repmgr version as it's not specific to a particular + * PostgreSQL version */ printf("%s %s\n", progname(), REPMGR_VERSION); exit(SUCCESS); - /*------------------------------ - * general configuration options - *------------------------------ - */ + /*------------------------------ + * general configuration options + *------------------------------ + */ - /* -b/--pg_bindir */ + /* -b/--pg_bindir */ case 'b': strncpy(runtime_options.pg_bindir, optarg, MAXLEN); break; - /* -f/--config-file */ + /* -f/--config-file */ case 'f': strncpy(runtime_options.config_file, optarg, MAXLEN); break; - /* --dry-run */ + /* --dry-run */ case OPT_DRY_RUN: runtime_options.dry_run = true; break; - /* -F/--force */ + /* -F/--force */ case 'F': runtime_options.force = true; break; - /* --replication-user (primary/standby register only) */ + /* --replication-user (primary/standby register only) */ case OPT_REPLICATION_USER: strncpy(runtime_options.replication_user, optarg, MAXLEN); break; - /* -W/--wait */ + /* -W/--wait */ case 'W': runtime_options.wait = true; break; - /*---------------------------- - * database connection options - *---------------------------- - */ + /*---------------------------- + * database connection options + *---------------------------- + */ - /* - * These are the standard database connection options; with the - * exception of -d/--dbname (which could be a conninfo string) - * we'll also set these values in "source_conninfo" (overwriting - * preset values from environment variables). - * XXX check this is same as psql - */ - /* -d/--dbname */ + /* + * These are the standard database connection options; with + * the exception of -d/--dbname (which could be a conninfo + * string) we'll also set these values in "source_conninfo" + * (overwriting preset values from environment variables). XXX + * check this is same as psql + */ + /* -d/--dbname */ case 'd': strncpy(runtime_options.dbname, optarg, MAXLEN); - /* dbname will be set in source_conninfo later after checking if it's a conninfo string */ + + /* + * dbname will be set in source_conninfo later after checking + * if it's a conninfo string + */ runtime_options.connection_param_provided = true; break; - /* -h/--host */ + /* -h/--host */ case 'h': strncpy(runtime_options.host, optarg, MAXLEN); param_set(&source_conninfo, "host", optarg); @@ -280,67 +285,68 @@ main(int argc, char **argv) runtime_options.connection_param_provided = true; break; - /* -U/--user */ + /* -U/--user */ case 'U': strncpy(runtime_options.username, optarg, MAXLEN); param_set(&source_conninfo, "user", optarg); runtime_options.connection_param_provided = true; break; - /*------------------------- - * other connection options - *------------------------- - */ + /*------------------------- + * other connection options + *------------------------- + */ - /* -R/--remote_user */ + /* -R/--remote_user */ case 'R': strncpy(runtime_options.remote_user, optarg, MAXLEN); break; - /* -S/--superuser */ + /* -S/--superuser */ case 'S': strncpy(runtime_options.superuser, optarg, MAXLEN); break; - /*------------- - * node options - *------------- - */ + /*------------- + * node options + *------------- + */ - /* -D/--pgdata/--data-dir */ + /* -D/--pgdata/--data-dir */ case 'D': strncpy(runtime_options.data_dir, optarg, MAXPGPATH); break; - /* --node-id */ + /* --node-id */ case OPT_NODE_ID: runtime_options.node_id = repmgr_atoi(optarg, "--node-id", &cli_errors, false); break; - /* --node-name */ + /* --node-name */ case OPT_NODE_NAME: strncpy(runtime_options.node_name, optarg, MAXLEN); break; - /* standby options * - * --------------- */ + /* + * standby options * --------------- + */ - /* --upstream-node-id */ + /* --upstream-node-id */ case OPT_UPSTREAM_NODE_ID: runtime_options.upstream_node_id = repmgr_atoi(optarg, "--upstream-node-id", &cli_errors, false); break; - /*------------------------ - * "standby clone" options - *------------------------ - */ + /*------------------------ + * "standby clone" options + *------------------------ + */ - /* -c/--fast-checkpoint */ + /* -c/--fast-checkpoint */ case 'c': runtime_options.fast_checkpoint = true; break; - /* --copy-external-config-files(=[samepath|pgdata]) */ + /* --copy-external-config-files(=[samepath|pgdata]) */ case OPT_COPY_EXTERNAL_CONFIG_FILES: runtime_options.copy_external_config_files = true; if (optarg != NULL) @@ -362,7 +368,7 @@ main(int argc, char **argv) } break; - /* --no-upstream-connection */ + /* --no-upstream-connection */ case OPT_NO_UPSTREAM_CONNECTION: runtime_options.no_upstream_connection = true; break; @@ -376,10 +382,10 @@ main(int argc, char **argv) runtime_options.without_barman = true; break; - /*--------------------------- - * "standby register" options - *--------------------------- - */ + /*--------------------------- + * "standby register" options + *--------------------------- + */ case OPT_REGISTER_WAIT: runtime_options.wait_register_sync = true; @@ -389,10 +395,10 @@ main(int argc, char **argv) } break; - /*----------------------------- - * "standby switchover" options - *----------------------------- - */ + /*----------------------------- + * "standby switchover" options + *----------------------------- + */ case OPT_ALWAYS_PROMOTE: runtime_options.always_promote = true; @@ -406,19 +412,19 @@ main(int argc, char **argv) runtime_options.siblings_follow = true; break; - /*---------------------- - * "node status" options - *---------------------- - */ + /*---------------------- + * "node status" options + *---------------------- + */ case OPT_IS_SHUTDOWN_CLEANLY: runtime_options.is_shutdown_cleanly = true; break; - /*--------------------- - * "node check" options - *-------------------- - */ + /*--------------------- + * "node check" options + *-------------------- + */ case OPT_ARCHIVE_READY: runtime_options.archive_ready = true; break; @@ -439,26 +445,26 @@ main(int argc, char **argv) runtime_options.slots = true; break; - /*-------------------- - * "node rejoin" options - *-------------------- - */ + /*-------------------- + * "node rejoin" options + *-------------------- + */ case OPT_CONFIG_FILES: strncpy(runtime_options.config_files, optarg, MAXLEN); break; - /* internal options */ + /* internal options */ case OPT_CONFIG_ARCHIVE_DIR: /* TODO: check this is an absolute path */ strncpy(runtime_options.config_archive_dir, optarg, MAXPGPATH); break; - /*----------------------- - * "node service" options - *----------------------- - */ + /*----------------------- + * "node service" options + *----------------------- + */ - /* --action (repmgr node service --action) */ + /* --action (repmgr node service --action) */ case OPT_ACTION: strncpy(runtime_options.action, optarg, MAXLEN); break; @@ -475,10 +481,10 @@ main(int argc, char **argv) runtime_options.checkpoint = true; break; - /*------------------------ - * "cluster event" options - *------------------------ - */ + /*------------------------ + * "cluster event" options + *------------------------ + */ case OPT_EVENT: strncpy(runtime_options.event, optarg, MAXLEN); @@ -493,51 +499,53 @@ main(int argc, char **argv) runtime_options.all = true; break; - /*---------------- - * logging options - *---------------- - */ + /*---------------- + * logging options + *---------------- + */ - /* -L/--log-level */ + /* -L/--log-level */ case 'L': - { - int detected_log_level = detect_log_level(optarg); - if (detected_log_level != -1) { - strncpy(runtime_options.log_level, optarg, MAXLEN); - } - else - { - PQExpBufferData invalid_log_level; - initPQExpBuffer(&invalid_log_level); - appendPQExpBuffer(&invalid_log_level, _("invalid log level \"%s\" provided"), optarg); - item_list_append(&cli_errors, invalid_log_level.data); - termPQExpBuffer(&invalid_log_level); - } - break; - } + int detected_log_level = detect_log_level(optarg); - /* --log-to-file */ + if (detected_log_level != -1) + { + strncpy(runtime_options.log_level, optarg, MAXLEN); + } + else + { + PQExpBufferData invalid_log_level; + + initPQExpBuffer(&invalid_log_level); + appendPQExpBuffer(&invalid_log_level, _("invalid log level \"%s\" provided"), optarg); + item_list_append(&cli_errors, invalid_log_level.data); + termPQExpBuffer(&invalid_log_level); + } + break; + } + + /* --log-to-file */ case OPT_LOG_TO_FILE: runtime_options.log_to_file = true; logger_output_mode = OM_DAEMON; break; - /* --terse */ + /* --terse */ case 't': runtime_options.terse = true; break; - /* --verbose */ + /* --verbose */ case 'v': runtime_options.verbose = true; break; - /*-------------- - * output options - *--------------- - */ + /*-------------- + * output options + *--------------- + */ case OPT_CSV: runtime_options.csv = true; break; @@ -550,10 +558,10 @@ main(int argc, char **argv) runtime_options.optformat = true; break; - /*----------------------------- - * options deprecated since 3.3 - *----------------------------- - */ + /*----------------------------- + * options deprecated since 3.3 + *----------------------------- + */ case OPT_DATA_DIR: item_list_append(&cli_warnings, _("--data-dir is deprecated; use -D/--pgdata instead")); @@ -562,13 +570,13 @@ main(int argc, char **argv) item_list_append(&cli_warnings, _("--no-conninfo-password is deprecated; pasuse --use-recovery-conninfo-password to explicitly set a password")); break; - /* -C/--remote-config-file */ + /* -C/--remote-config-file */ case 'C': item_list_append(&cli_warnings, _("--remote-config-file is no longer required")); break; - /* --recovery-min-apply-delay */ + /* --recovery-min-apply-delay */ case OPT_RECOVERY_MIN_APPLY_DELAY: item_list_append(&cli_warnings, _("--recovery-min-apply-delay is now a configuration file parameter, \"recovery_min_apply_delay\"")); @@ -584,8 +592,8 @@ main(int argc, char **argv) if (runtime_options.dbname) { if (strncmp(runtime_options.dbname, "postgresql://", 13) == 0 || - strncmp(runtime_options.dbname, "postgres://", 11) == 0 || - strchr(runtime_options.dbname, '=') != NULL) + strncmp(runtime_options.dbname, "postgres://", 11) == 0 || + strchr(runtime_options.dbname, '=') != NULL) { char *errmsg = NULL; PQconninfoOption *opts; @@ -597,6 +605,7 @@ main(int argc, char **argv) if (opts == NULL) { PQExpBufferData conninfo_error; + initPQExpBuffer(&conninfo_error); appendPQExpBuffer(&conninfo_error, _("error parsing conninfo:\n%s"), errmsg); item_list_append(&cli_errors, conninfo_error.data); @@ -613,6 +622,7 @@ main(int argc, char **argv) * settings take priority */ PQconninfoOption *opt; + for (opt = opts; opt->keyword != NULL; opt++) { if (opt->val != NULL && opt->val[0] != '\0') @@ -649,14 +659,14 @@ main(int argc, char **argv) } else { - param_set(&source_conninfo, "dbname", runtime_options.dbname); + param_set(&source_conninfo, "dbname", runtime_options.dbname); } } /* - * Disallow further running as root to prevent directory ownership problems. - * We check this here to give the root user a chance to execute --help/--version - * options. + * Disallow further running as root to prevent directory ownership + * problems. We check this here to give the root user a chance to execute + * --help/--version options. */ if (geteuid() == 0 && help_option == false) { @@ -665,7 +675,7 @@ main(int argc, char **argv) "Please log in (using, e.g., \"su\") as the " "(unprivileged) user that owns " "the data directory.\n" - ), + ), progname()); free_conninfo_params(&source_conninfo); exit(ERR_BAD_CONFIG); @@ -681,13 +691,14 @@ main(int argc, char **argv) /* * Determine the node type and action; following are valid: * - * { PRIMARY | MASTER } REGISTER | - * STANDBY {REGISTER | UNREGISTER | CLONE [node] | PROMOTE | FOLLOW [node] | SWITCHOVER | REWIND} | - * BDR { REGISTER | UNREGISTER } | - * NODE { STATUS | CHECK | REJOIN | ARCHIVE-CONFIG | RESTORE-CONFIG | SERVICE } | - * CLUSTER { CROSSCHECK | MATRIX | SHOW | CLEANUP | EVENT } + * { PRIMARY | MASTER } REGISTER | STANDBY {REGISTER | UNREGISTER | CLONE + * [node] | PROMOTE | FOLLOW [node] | SWITCHOVER | REWIND} | BDR { + * REGISTER | UNREGISTER } | NODE { STATUS | CHECK | REJOIN | + * ARCHIVE-CONFIG | RESTORE-CONFIG | SERVICE } | CLUSTER { CROSSCHECK | + * MATRIX | SHOW | CLEANUP | EVENT } * - * [node] is an optional hostname, provided instead of the -h/--host option + * [node] is an optional hostname, provided instead of the -h/--host + * option */ if (optind < argc) { @@ -706,7 +717,7 @@ main(int argc, char **argv) if (repmgr_command != NULL) { #ifndef BDR_ONLY - if (strcasecmp(repmgr_command, "PRIMARY") == 0 || strcasecmp(repmgr_command, "MASTER") == 0 ) + if (strcasecmp(repmgr_command, "PRIMARY") == 0 || strcasecmp(repmgr_command, "MASTER") == 0) { if (help_option == true) { @@ -778,7 +789,7 @@ main(int argc, char **argv) exit(SUCCESS); } - if (strcasecmp(repmgr_action, "CHECK") == 0) + if (strcasecmp(repmgr_action, "CHECK") == 0) action = NODE_CHECK; else if (strcasecmp(repmgr_action, "STATUS") == 0) action = NODE_STATUS; @@ -823,6 +834,7 @@ main(int argc, char **argv) if (action == NO_ACTION) { PQExpBufferData command_error; + initPQExpBuffer(&command_error); if (repmgr_command == NULL) @@ -838,9 +850,9 @@ main(int argc, char **argv) } else if (repmgr_action[0] == '\0') { - appendPQExpBuffer(&command_error, - _("no action provided for command '%s'"), - repmgr_command); + appendPQExpBuffer(&command_error, + _("no action provided for command '%s'"), + repmgr_command); } else { @@ -853,7 +865,10 @@ main(int argc, char **argv) item_list_append(&cli_errors, command_error.data); } - /* STANDBY CLONE historically accepts the upstream hostname as an additional argument */ + /* + * STANDBY CLONE historically accepts the upstream hostname as an + * additional argument + */ if (action == STANDBY_CLONE) { if (optind < argc) @@ -861,6 +876,7 @@ main(int argc, char **argv) if (runtime_options.host_param_provided == true) { PQExpBufferData additional_host_arg; + initPQExpBuffer(&additional_host_arg); appendPQExpBuffer(&additional_host_arg, _("host name provided both with %s and as an extra parameter"), @@ -879,6 +895,7 @@ main(int argc, char **argv) if (optind < argc) { PQExpBufferData too_many_args; + initPQExpBuffer(&too_many_args); appendPQExpBuffer(&too_many_args, _("too many command-line arguments (first extra is \"%s\")"), argv[optind]); item_list_append(&cli_errors, too_many_args.data); @@ -886,9 +903,9 @@ main(int argc, char **argv) /* - * The configuration file is not required for some actions (e.g. 'standby clone'), - * however if available we'll parse it anyway for options like 'log_level', - * 'use_replication_slots' etc. + * The configuration file is not required for some actions (e.g. 'standby + * clone'), however if available we'll parse it anyway for options like + * 'log_level', 'use_replication_slots' etc. */ load_config(runtime_options.config_file, runtime_options.verbose, @@ -899,8 +916,8 @@ main(int argc, char **argv) check_cli_parameters(action); /* - * Sanity checks for command line parameters completed by now; - * any further errors will be runtime ones + * Sanity checks for command line parameters completed by now; any further + * errors will be runtime ones */ if (cli_errors.head != NULL) { @@ -909,8 +926,8 @@ main(int argc, char **argv) } /* - * Print any warnings about inappropriate command line options, - * unless -t/--terse set + * Print any warnings about inappropriate command line options, unless + * -t/--terse set */ if (cli_warnings.head != NULL && runtime_options.terse == false) { @@ -918,8 +935,10 @@ main(int argc, char **argv) print_item_list(&cli_warnings); } - /* post-processing following command line parameter checks - * ======================================================= */ + /* + * post-processing following command line parameter checks + * ======================================================= + */ if (runtime_options.csv == true) { @@ -953,18 +972,27 @@ main(int argc, char **argv) } - /* Check for configuration file items which can be overriden by runtime options */ - /* ============================================================================ */ + /* + * Check for configuration file items which can be overriden by runtime + * options + */ - /* Command-line parameter -L/--log-level overrides any setting in config file*/ + /* + * ============================================================================ + */ + + /* + * Command-line parameter -L/--log-level overrides any setting in config + * file + */ if (*runtime_options.log_level != '\0') { strncpy(config_file_options.log_level, runtime_options.log_level, MAXLEN); } /* - * Initialise pg_bindir - command line parameter will override - * any setting in the configuration file + * Initialise pg_bindir - command line parameter will override any setting + * in the configuration file */ if (!strlen(runtime_options.pg_bindir)) { @@ -974,7 +1002,8 @@ main(int argc, char **argv) /* Add trailing slash */ if (strlen(runtime_options.pg_bindir)) { - int len = strlen(runtime_options.pg_bindir); + int len = strlen(runtime_options.pg_bindir); + if (runtime_options.pg_bindir[len - 1] != '/') { maxlen_snprintf(pg_bindir, "%s/", runtime_options.pg_bindir); @@ -987,11 +1016,12 @@ main(int argc, char **argv) /* * Initialize the logger. We've previously requested STDERR logging only - * to ensure the repmgr command doesn't have its output diverted to a logging - * facility (which usually doesn't make sense for a command line program). + * to ensure the repmgr command doesn't have its output diverted to a + * logging facility (which usually doesn't make sense for a command line + * program). * - * If required (e.g. when calling repmgr from repmgrd), this behaviour can be - * overridden with "--log-to-file". + * If required (e.g. when calling repmgr from repmgrd), this behaviour can + * be overridden with "--log-to-file". */ logger_init(&config_file_options, progname()); @@ -1025,17 +1055,17 @@ main(int argc, char **argv) * If a node was specified (by --node-id or --node-name), check it exists * (and pre-populate a record for later use). * - * At this point check_cli_parameters() will already have determined - * if provision of these is valid for the action, otherwise it unsets them. + * At this point check_cli_parameters() will already have determined if + * provision of these is valid for the action, otherwise it unsets them. * - * We need to check this much later than other command line parameters - * as we need to wait until the configuration file is parsed and we can + * We need to check this much later than other command line parameters as + * we need to wait until the configuration file is parsed and we can * obtain the conninfo string. */ if (runtime_options.node_id != UNKNOWN_NODE_ID || runtime_options.node_name[0] != '\0') { - PGconn *conn = NULL; + PGconn *conn = NULL; RecordStatus record_status = RECORD_NOT_FOUND; log_verbose(LOG_DEBUG, "connecting to local node to retrieve record for node specified with --node-id or --node-name"); @@ -1061,7 +1091,8 @@ main(int argc, char **argv) } else if (runtime_options.node_name[0] != '\0') { - char *escaped = escape_string(conn, runtime_options.node_name); + char *escaped = escape_string(conn, runtime_options.node_name); + if (escaped == NULL) { log_error(_("unable to escape value provided for --node-name")); @@ -1092,7 +1123,7 @@ main(int argc, char **argv) switch (action) { #ifndef BDR_ONLY - /* PRIMARY */ + /* PRIMARY */ case PRIMARY_REGISTER: do_primary_register(); break; @@ -1100,7 +1131,7 @@ main(int argc, char **argv) do_primary_unregister(); break; - /* STANDBY */ + /* STANDBY */ case STANDBY_CLONE: do_standby_clone(); break; @@ -1122,7 +1153,7 @@ main(int argc, char **argv) break; #else - /* we won't ever reach here, but stop the compiler complaining */ + /* we won't ever reach here, but stop the compiler complaining */ case PRIMARY_REGISTER: case PRIMARY_UNREGISTER: case STANDBY_CLONE: @@ -1134,7 +1165,7 @@ main(int argc, char **argv) break; #endif - /* BDR */ + /* BDR */ case BDR_REGISTER: do_bdr_register(); break; @@ -1142,7 +1173,7 @@ main(int argc, char **argv) do_bdr_unregister(); break; - /* NODE */ + /* NODE */ case NODE_STATUS: do_node_status(); break; @@ -1156,7 +1187,7 @@ main(int argc, char **argv) do_node_service(); break; - /* CLUSTER */ + /* CLUSTER */ case CLUSTER_SHOW: do_cluster_show(); break; @@ -1196,7 +1227,8 @@ main(int argc, char **argv) static void check_cli_parameters(const int action) { - /* ======================================================================== + /* + * ======================================================================== * check all parameters required for an action are provided, and warn * about ineffective actions * ======================================================================== @@ -1207,91 +1239,95 @@ check_cli_parameters(const int action) /* no required parameters */ break; case STANDBY_CLONE: - { - standy_clone_mode mode = get_standby_clone_mode(); - - config_file_required = false; - - if (mode == barman) { - if (runtime_options.copy_external_config_files) + standy_clone_mode mode = get_standby_clone_mode(); + + config_file_required = false; + + if (mode == barman) { - item_list_append(&cli_warnings, - _("--copy-external-config-files ineffective in Barman mode")); - } - - if (runtime_options.fast_checkpoint) - { - item_list_append(&cli_warnings, - _("-c/--fast-checkpoint has no effect in Barman mode")); - } - - - } - else - { - if (!runtime_options.host_param_provided) - { - item_list_append_format(&cli_errors, - _("host name for the source node must be provided when executing %s"), - action_name(action)); - } - - if (!runtime_options.connection_param_provided) - { - item_list_append_format(&cli_errors, - _("database connection parameters for the source node must be provided when executing %s"), - action_name(action)); - } - - // XXX if -D/--pgdata provided, and also config_file_options.pgdaga, warn -D/--pgdata will be ignored - - if (*runtime_options.upstream_conninfo) - { - if (*runtime_options.replication_user) + if (runtime_options.copy_external_config_files) { item_list_append(&cli_warnings, - _("--replication-user ineffective when specifying --upstream-conninfo")); + _("--copy-external-config-files ineffective in Barman mode")); + } + + if (runtime_options.fast_checkpoint) + { + item_list_append(&cli_warnings, + _("-c/--fast-checkpoint has no effect in Barman mode")); + } + + + } + else + { + if (!runtime_options.host_param_provided) + { + item_list_append_format(&cli_errors, + _("host name for the source node must be provided when executing %s"), + action_name(action)); + } + + if (!runtime_options.connection_param_provided) + { + item_list_append_format(&cli_errors, + _("database connection parameters for the source node must be provided when executing %s"), + action_name(action)); + } + + /* + * XXX if -D/--pgdata provided, and also + * config_file_options.pgdaga, warn -D/--pgdata will be + * ignored + */ + + if (*runtime_options.upstream_conninfo) + { + if (*runtime_options.replication_user) + { + item_list_append(&cli_warnings, + _("--replication-user ineffective when specifying --upstream-conninfo")); + } + } + + if (runtime_options.no_upstream_connection == true) + { + item_list_append(&cli_warnings, + _("--no-upstream-connection only effective in Barman mode")); } } - - if (runtime_options.no_upstream_connection == true) - { - item_list_append(&cli_warnings, - _("--no-upstream-connection only effective in Barman mode")); - } } - } - break; + break; case STANDBY_FOLLOW: - { - /* - * if `repmgr standby follow` executed with host params, ensure data - * directory was provided - */ - } - break; + { + /* + * if `repmgr standby follow` executed with host params, + * ensure data directory was provided + */ + } + break; case NODE_STATUS: if (runtime_options.node_id != UNKNOWN_NODE_ID) { item_list_append( - &cli_warnings, - "--node-id will be ignored; \"repmgr node status\" can only be executed on the local node"); + &cli_warnings, + "--node-id will be ignored; \"repmgr node status\" can only be executed on the local node"); } if (runtime_options.node_name[0] != '\0') { item_list_append( - &cli_warnings, - "--node-name will be ignored; \"repmgr node status\" can only be executed on the local node"); + &cli_warnings, + "--node-name will be ignored; \"repmgr node status\" can only be executed on the local node"); } break; case NODE_REJOIN: if (runtime_options.connection_param_provided == false) { item_list_append( - &cli_errors, - "database connection parameters for an available node must be provided when executing NODE REJOIN"); + &cli_errors, + "database connection parameters for an available node must be provided when executing NODE REJOIN"); } break; case CLUSTER_SHOW: @@ -1306,12 +1342,13 @@ check_cli_parameters(const int action) } - /* ======================================================================== + /* + * ======================================================================== * warn if parameters provided for an action where they're not relevant * ======================================================================== */ - /* --host etc.*/ + /* --host etc. */ if (runtime_options.connection_param_provided) { switch (action) @@ -1499,9 +1536,9 @@ check_cli_parameters(const int action) break; default: item_list_append_format( - &cli_warnings, - _("--is-shutdown-cleanly will be ignored when executing %s"), - action_name(action)); + &cli_warnings, + _("--is-shutdown-cleanly will be ignored when executing %s"), + action_name(action)); } } @@ -1513,9 +1550,9 @@ check_cli_parameters(const int action) break; default: item_list_append_format( - &cli_warnings, - _("--always-promote will be ignored when executing %s"), - action_name(action)); + &cli_warnings, + _("--always-promote will be ignored when executing %s"), + action_name(action)); } } @@ -1528,9 +1565,9 @@ check_cli_parameters(const int action) break; default: item_list_append_format( - &cli_warnings, - _("--force-rewind will be ignored when executing %s"), - action_name(action)); + &cli_warnings, + _("--force-rewind will be ignored when executing %s"), + action_name(action)); } } @@ -1543,9 +1580,9 @@ check_cli_parameters(const int action) break; default: item_list_append_format( - &cli_warnings, - _("--config-files will be ignored when executing %s"), - action_name(action)); + &cli_warnings, + _("--config-files will be ignored when executing %s"), + action_name(action)); } } @@ -1562,40 +1599,40 @@ check_cli_parameters(const int action) break; default: item_list_append_format( - &cli_warnings, - _("--dry-run is not effective when executing %s"), - action_name(action)); + &cli_warnings, + _("--dry-run is not effective when executing %s"), + action_name(action)); } } /* check only one of --csv, --nagios and --optformat used */ { - int used_options = 0; + int used_options = 0; if (runtime_options.csv == true) - used_options ++; + used_options++; if (runtime_options.nagios == true) - used_options ++; + used_options++; if (runtime_options.optformat == true) - used_options ++; + used_options++; if (used_options > 1) { /* TODO: list which options were used */ item_list_append( - &cli_errors, - "only one of --csv, --nagios and --optformat can be used"); + &cli_errors, + "only one of --csv, --nagios and --optformat can be used"); } } } -static const char* +static const char * action_name(const int action) { - switch(action) + switch (action) { case PRIMARY_REGISTER: return "PRIMARY REGISTER"; @@ -1648,14 +1685,14 @@ print_error_list(ItemList *error_list, int log_level) for (cell = error_list->head; cell; cell = cell->next) { - switch(log_level) + switch (log_level) { - /* Currently we only need errors and warnings */ + /* Currently we only need errors and warnings */ case LOG_ERROR: - log_error("%s", cell->string); + log_error("%s", cell->string); break; case LOG_WARNING: - log_warning("%s", cell->string); + log_warning("%s", cell->string); break; } } @@ -1760,19 +1797,19 @@ do_help(void) bool create_repmgr_extension(PGconn *conn) { - PQExpBufferData query; - PGresult *res; + PQExpBufferData query; + PGresult *res; - ExtensionStatus extension_status = REPMGR_UNKNOWN; + ExtensionStatus extension_status = REPMGR_UNKNOWN; - t_connection_user userinfo = T_CONNECTION_USER_INITIALIZER; - bool is_superuser = false; - PGconn *superuser_conn = NULL; - PGconn *schema_create_conn = NULL; + t_connection_user userinfo = T_CONNECTION_USER_INITIALIZER; + bool is_superuser = false; + PGconn *superuser_conn = NULL; + PGconn *schema_create_conn = NULL; extension_status = get_repmgr_extension_status(conn); - switch(extension_status) + switch (extension_status) { case REPMGR_UNKNOWN: log_error(_("unable to determine status of \"repmgr\" extension")); @@ -1887,11 +1924,11 @@ create_repmgr_extension(PGconn *conn) log_notice(_("\"repmgr\" extension successfully installed")); create_event_notification(conn, - &config_file_options, - config_file_options.node_id, - "cluster_created", - true, - NULL); + &config_file_options, + config_file_options.node_id, + "cluster_created", + true, + NULL); return true; } @@ -1948,12 +1985,13 @@ int test_ssh_connection(char *host, char *remote_user) { char script[MAXLEN] = ""; - int r = 1, i; + int r = 1, + i; - /* On some OS, true is located in a different place than in Linux - * we have to try them all until all alternatives are gone or we - * found `true' because the target OS may differ from the source - * OS + /* + * On some OS, true is located in a different place than in Linux we have + * to try them all until all alternatives are gone or we found `true' + * because the target OS may differ from the source OS */ const char *bin_true_paths[] = { "/bin/true", @@ -1989,9 +2027,9 @@ test_ssh_connection(char *host, char *remote_user) bool local_command(const char *command, PQExpBufferData *outputbuf) { - FILE *fp; - char output[MAXLEN]; - int retval = 0; + FILE *fp; + char output[MAXLEN]; + int retval = 0; if (outputbuf == NULL) { @@ -2028,7 +2066,7 @@ void get_superuser_connection(PGconn **conn, PGconn **superuser_conn, PGconn **privileged_conn) { t_connection_user userinfo = T_CONNECTION_USER_INITIALIZER; - bool is_superuser = false; + bool is_superuser = false; /* this should never happen */ if (PQstatus(*conn) != CONNECTION_OK) @@ -2054,8 +2092,8 @@ get_superuser_connection(PGconn **conn, PGconn **superuser_conn, PGconn **privil } *superuser_conn = establish_db_connection_as_user(config_file_options.conninfo, - runtime_options.superuser, - false); + runtime_options.superuser, + false); if (PQstatus(*superuser_conn) != CONNECTION_OK) { @@ -2108,7 +2146,7 @@ int copy_remote_files(char *host, char *remote_user, char *remote_path, char *local_path, bool is_directory, int server_version_num) { - PQExpBufferData rsync_flags; + PQExpBufferData rsync_flags; char script[MAXLEN] = ""; char host_string[MAXLEN] = ""; int r = 0; @@ -2142,12 +2180,12 @@ copy_remote_files(char *host, char *remote_user, char *remote_path, } /* - * When copying the main PGDATA directory, certain files and contents - * of certain directories need to be excluded. + * When copying the main PGDATA directory, certain files and contents of + * certain directories need to be excluded. * * See function 'sendDir()' in 'src/backend/replication/basebackup.c' - - * we're basically simulating what pg_basebackup does, but with rsync rather - * than the BASEBACKUP replication protocol command. + * we're basically simulating what pg_basebackup does, but with rsync + * rather than the BASEBACKUP replication protocol command. * * *However* currently we'll always copy the contents of the 'pg_replslot' * directory and delete later if appropriate. @@ -2267,14 +2305,16 @@ create_recovery_file(t_node_info *node_record, t_conninfo_param_list *recovery_c */ if (strlen(runtime_options.upstream_conninfo)) { - char *escaped = escape_recovery_conf_value(runtime_options.upstream_conninfo); + char *escaped = escape_recovery_conf_value(runtime_options.upstream_conninfo); + maxlen_snprintf(line, "primary_conninfo = '%s'\n", escaped); free(escaped); } + /* - * otherwise use the conninfo inferred from the upstream connection - * and/or node record + * otherwise use the conninfo inferred from the upstream connection and/or + * node record */ else { @@ -2320,13 +2360,16 @@ create_recovery_file(t_node_info *node_record, t_conninfo_param_list *recovery_c log_debug("recovery.conf: %s", line); } - /* If restore_command is set, we use it as restore_command in recovery.conf */ + /* + * If restore_command is set, we use it as restore_command in + * recovery.conf + */ if (strcmp(config_file_options.restore_command, "") != 0) { maxlen_snprintf(line, "restore_command = '%s'\n", config_file_options.restore_command); if (write_recovery_file_line(recovery_file, recovery_file_path, line) == false) - return false; + return false; trim(line); log_debug("recovery.conf: %s", line); @@ -2355,10 +2398,10 @@ static void write_primary_conninfo(char *line, t_conninfo_param_list *param_list) { PQExpBufferData conninfo_buf; - bool application_name_provided = false; - bool password_provided = false; - int c; - char *escaped = NULL; + bool application_name_provided = false; + bool password_provided = false; + int c; + char *escaped = NULL; t_conninfo_param_list env_conninfo; initialize_conninfo_params(&env_conninfo, true); @@ -2372,9 +2415,9 @@ write_primary_conninfo(char *line, t_conninfo_param_list *param_list) * recovery.conf */ if (strcmp(param_list->keywords[c], "dbname") == 0 || - strcmp(param_list->keywords[c], "replication") == 0 || - (param_list->values[c] == NULL) || - (param_list->values[c] != NULL && param_list->values[c][0] == '\0')) + strcmp(param_list->keywords[c], "replication") == 0 || + (param_list->values[c] == NULL) || + (param_list->values[c] != NULL && param_list->values[c][0] == '\0')) continue; /* only include "password" if explicitly requested */ @@ -2399,7 +2442,7 @@ write_primary_conninfo(char *line, t_conninfo_param_list *param_list) if (strlen(config_file_options.node_name)) { appendPQExpBuffer(&conninfo_buf, " application_name="); - appendConnStrVal(&conninfo_buf, config_file_options.node_name); + appendConnStrVal(&conninfo_buf, config_file_options.node_name); } else { @@ -2439,11 +2482,11 @@ write_primary_conninfo(char *line, t_conninfo_param_list *param_list) bool remote_command(const char *host, const char *user, const char *command, PQExpBufferData *outputbuf) { - FILE *fp; - char ssh_command[MAXLEN] = ""; + FILE *fp; + char ssh_command[MAXLEN] = ""; PQExpBufferData ssh_host; - char output[MAXLEN] = ""; + char output[MAXLEN] = ""; initPQExpBuffer(&ssh_host); @@ -2523,169 +2566,169 @@ get_server_action(t_server_action action, char *script, char *data_dir) if (data_dir == NULL || data_dir[0] == '\0') data_dir = "(none provided)"; - switch(action) + switch (action) { case ACTION_NONE: script[0] = '\0'; return; case ACTION_START: - { - if (config_file_options.service_start_command[0] != '\0') { - maxlen_snprintf(script, "%s", - config_file_options.service_start_command); + if (config_file_options.service_start_command[0] != '\0') + { + maxlen_snprintf(script, "%s", + config_file_options.service_start_command); + } + else + { + initPQExpBuffer(&command); + + appendPQExpBuffer( + &command, + "%s %s -w -D ", + make_pg_path("pg_ctl"), + config_file_options.pg_ctl_options); + + appendShellString( + &command, + data_dir); + + appendPQExpBuffer( + &command, + " start"); + + strncpy(script, command.data, MAXLEN); + + termPQExpBuffer(&command); + } + + return; } - else - { - initPQExpBuffer(&command); - - appendPQExpBuffer( - &command, - "%s %s -w -D ", - make_pg_path("pg_ctl"), - config_file_options.pg_ctl_options); - - appendShellString( - &command, - data_dir); - - appendPQExpBuffer( - &command, - " start"); - - strncpy(script, command.data, MAXLEN); - - termPQExpBuffer(&command); - } - - return; - } case ACTION_STOP: - { - if (config_file_options.service_stop_command[0] != '\0') { - maxlen_snprintf(script, "%s", - config_file_options.service_stop_command); + if (config_file_options.service_stop_command[0] != '\0') + { + maxlen_snprintf(script, "%s", + config_file_options.service_stop_command); + } + else + { + initPQExpBuffer(&command); + appendPQExpBuffer( + &command, + "%s %s -D ", + make_pg_path("pg_ctl"), + config_file_options.pg_ctl_options); + + appendShellString( + &command, + data_dir); + + appendPQExpBuffer( + &command, + " -m fast -W stop"); + + strncpy(script, command.data, MAXLEN); + + termPQExpBuffer(&command); + } + return; } - else - { - initPQExpBuffer(&command); - appendPQExpBuffer( - &command, - "%s %s -D ", - make_pg_path("pg_ctl"), - config_file_options.pg_ctl_options); - - appendShellString( - &command, - data_dir); - - appendPQExpBuffer( - &command, - " -m fast -W stop"); - - strncpy(script, command.data, MAXLEN); - - termPQExpBuffer(&command); - } - return; - } case ACTION_RESTART: - { - if (config_file_options.service_restart_command[0] != '\0') { - maxlen_snprintf(script, "%s", - config_file_options.service_restart_command); + if (config_file_options.service_restart_command[0] != '\0') + { + maxlen_snprintf(script, "%s", + config_file_options.service_restart_command); + } + else + { + initPQExpBuffer(&command); + appendPQExpBuffer( + &command, + "%s %s -w -D ", + make_pg_path("pg_ctl"), + config_file_options.pg_ctl_options); + + appendShellString( + &command, + data_dir); + + appendPQExpBuffer( + &command, + " restart"); + + strncpy(script, command.data, MAXLEN); + + termPQExpBuffer(&command); + } + return; } - else - { - initPQExpBuffer(&command); - appendPQExpBuffer( - &command, - "%s %s -w -D ", - make_pg_path("pg_ctl"), - config_file_options.pg_ctl_options); - - appendShellString( - &command, - data_dir); - - appendPQExpBuffer( - &command, - " restart"); - - strncpy(script, command.data, MAXLEN); - - termPQExpBuffer(&command); - } - return; - } case ACTION_RELOAD: - { - if (config_file_options.service_reload_command[0] != '\0') { - maxlen_snprintf(script, "%s", - config_file_options.service_reload_command); + if (config_file_options.service_reload_command[0] != '\0') + { + maxlen_snprintf(script, "%s", + config_file_options.service_reload_command); + } + else + { + initPQExpBuffer(&command); + appendPQExpBuffer( + &command, + "%s %s -w -D ", + make_pg_path("pg_ctl"), + config_file_options.pg_ctl_options); + + appendShellString( + &command, + data_dir); + + appendPQExpBuffer( + &command, + " reload"); + + strncpy(script, command.data, MAXLEN); + + termPQExpBuffer(&command); + + } + return; } - else - { - initPQExpBuffer(&command); - appendPQExpBuffer( - &command, - "%s %s -w -D ", - make_pg_path("pg_ctl"), - config_file_options.pg_ctl_options); - - appendShellString( - &command, - data_dir); - - appendPQExpBuffer( - &command, - " reload"); - - strncpy(script, command.data, MAXLEN); - - termPQExpBuffer(&command); - - } - return; - } case ACTION_PROMOTE: - { - if (config_file_options.service_promote_command[0] != '\0') { - maxlen_snprintf(script, "%s", - config_file_options.service_promote_command); + if (config_file_options.service_promote_command[0] != '\0') + { + maxlen_snprintf(script, "%s", + config_file_options.service_promote_command); + } + else + { + initPQExpBuffer(&command); + appendPQExpBuffer( + &command, + "%s %s -w -D ", + make_pg_path("pg_ctl"), + config_file_options.pg_ctl_options); + + appendShellString( + &command, + data_dir); + + appendPQExpBuffer( + &command, + " promote"); + + strncpy(script, command.data, MAXLEN); + + termPQExpBuffer(&command); + } + return; } - else - { - initPQExpBuffer(&command); - appendPQExpBuffer( - &command, - "%s %s -w -D ", - make_pg_path("pg_ctl"), - config_file_options.pg_ctl_options); - - appendShellString( - &command, - data_dir); - - appendPQExpBuffer( - &command, - " promote"); - - strncpy(script, command.data, MAXLEN); - - termPQExpBuffer(&command); - } - return; - } default: return; @@ -2698,7 +2741,7 @@ get_server_action(t_server_action action, char *script, char *data_dir) bool data_dir_required_for_action(t_server_action action) { - switch(action) + switch (action) { case ACTION_NONE: return false; @@ -2750,8 +2793,8 @@ void get_node_data_directory(char *data_dir_buf) { /* - * the configuration file setting has priority, and will always be - * set when a configuration file was provided + * the configuration file setting has priority, and will always be set + * when a configuration file was provided */ if (config_file_options.data_directory[0] != '\0') { @@ -2800,9 +2843,9 @@ init_node_record(t_node_info *node_record) else { /* use the "user" value from "conninfo" */ - char repluser[MAXLEN] = ""; + char repluser[MAXLEN] = ""; - (void)get_conninfo_value(config_file_options.conninfo, "user", repluser); + (void) get_conninfo_value(config_file_options.conninfo, "user", repluser); strncpy(node_record->repluser, repluser, NAMEDATALEN); } diff --git a/repmgr-client.h b/repmgr-client.h index cb326111..3158c961 100644 --- a/repmgr-client.h +++ b/repmgr-client.h @@ -141,22 +141,22 @@ static struct option long_options[] = /* "standby switchover" options */ {"remote-config-file", required_argument, NULL, 'C'}, - {"always-promote", no_argument, NULL, OPT_ALWAYS_PROMOTE }, - {"force-rewind", no_argument, NULL, OPT_FORCE_REWIND }, - {"siblings-follow", no_argument, NULL, OPT_SIBLINGS_FOLLOW }, + {"always-promote", no_argument, NULL, OPT_ALWAYS_PROMOTE}, + {"force-rewind", no_argument, NULL, OPT_FORCE_REWIND}, + {"siblings-follow", no_argument, NULL, OPT_SIBLINGS_FOLLOW}, /* "node status" options */ - {"is-shutdown-cleanly", no_argument, NULL, OPT_IS_SHUTDOWN_CLEANLY }, + {"is-shutdown-cleanly", no_argument, NULL, OPT_IS_SHUTDOWN_CLEANLY}, /* "node check" options */ - {"archive-ready", no_argument, NULL, OPT_ARCHIVE_READY }, - {"downstream", no_argument, NULL, OPT_DOWNSTREAM }, - {"replication-lag", no_argument, NULL, OPT_REPLICATION_LAG }, - {"role", no_argument, NULL, OPT_ROLE }, - {"slots", no_argument, NULL, OPT_SLOTS }, + {"archive-ready", no_argument, NULL, OPT_ARCHIVE_READY}, + {"downstream", no_argument, NULL, OPT_DOWNSTREAM}, + {"replication-lag", no_argument, NULL, OPT_REPLICATION_LAG}, + {"role", no_argument, NULL, OPT_ROLE}, + {"slots", no_argument, NULL, OPT_SLOTS}, /* "node join" options */ - {"config-files", required_argument, NULL, OPT_CONFIG_FILES }, + {"config-files", required_argument, NULL, OPT_CONFIG_FILES}, /* "node service" options */ {"action", required_argument, NULL, OPT_ACTION}, @@ -165,16 +165,16 @@ static struct option long_options[] = {"checkpoint", no_argument, NULL, OPT_CHECKPOINT}, /* "cluster event" options */ - {"all", no_argument, NULL, OPT_ALL }, - {"event", required_argument, NULL, OPT_EVENT }, - {"limit", required_argument, NULL, OPT_LIMIT }, + {"all", no_argument, NULL, OPT_ALL}, + {"event", required_argument, NULL, OPT_EVENT}, + {"limit", required_argument, NULL, OPT_LIMIT}, /* Following options for internal use */ {"config-archive-dir", required_argument, NULL, OPT_CONFIG_ARCHIVE_DIR}, /* deprecated */ {"no-conninfo-password", no_argument, NULL, OPT_NO_CONNINFO_PASSWORD}, - /* legacy alias for -D/--pgdata*/ + /* legacy alias for -D/--pgdata */ {"data-dir", required_argument, NULL, OPT_DATA_DIR}, /* --node-id */ {"node", required_argument, NULL, OPT_NODE}, @@ -204,4 +204,4 @@ static void check_cli_parameters(const int action); static void write_primary_conninfo(char *line, t_conninfo_param_list *param_list); static bool write_recovery_file_line(FILE *recovery_file, char *recovery_file_path, char *line); -#endif /* _REPMGR_CLIENT_H_ */ +#endif /* _REPMGR_CLIENT_H_ */ diff --git a/repmgr.c b/repmgr.c index c3a92e69..af54ecaf 100644 --- a/repmgr.c +++ b/repmgr.c @@ -49,7 +49,8 @@ PG_MODULE_MAGIC; -typedef enum { +typedef enum +{ LEADER_NODE, FOLLOWER_NODE, CANDIDATE_NODE @@ -59,16 +60,16 @@ typedef struct repmgrdSharedState { LWLockId lock; /* protects search/modification */ TimestampTz last_updated; - int local_node_id; + int local_node_id; /* streaming failover */ NodeState node_state; NodeVotingStatus voting_status; - int current_electoral_term; - int candidate_node_id; - bool follow_new_primary; + int current_electoral_term; + int candidate_node_id; + bool follow_new_primary; /* BDR failover */ - int bdr_failover_handler; -} repmgrdSharedState; + int bdr_failover_handler; +} repmgrdSharedState; static repmgrdSharedState *shared_state = NULL; @@ -81,40 +82,52 @@ void _PG_fini(void); static void repmgr_shmem_startup(void); Datum set_local_node_id(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(set_local_node_id); Datum standby_set_last_updated(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(standby_set_last_updated); Datum standby_get_last_updated(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(standby_get_last_updated); Datum request_vote(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(request_vote); Datum get_voting_status(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(get_voting_status); Datum set_voting_status_initiated(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(set_voting_status_initiated); Datum other_node_is_candidate(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(other_node_is_candidate); Datum notify_follow_primary(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(notify_follow_primary); Datum get_new_primary(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(get_new_primary); Datum reset_voting_status(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(reset_voting_status); Datum am_bdr_failover_handler(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(am_bdr_failover_handler); Datum unset_bdr_failover_handler(PG_FUNCTION_ARGS); + PG_FUNCTION_INFO_V1(unset_bdr_failover_handler); @@ -209,7 +222,7 @@ repmgr_shmem_startup(void) Datum set_local_node_id(PG_FUNCTION_ARGS) { - int local_node_id = PG_GETARG_INT32(0); + int local_node_id = PG_GETARG_INT32(0); if (!shared_state) PG_RETURN_NULL(); @@ -266,15 +279,15 @@ Datum request_vote(PG_FUNCTION_ARGS) { #ifndef BDR_ONLY - StringInfoData query; - XLogRecPtr our_lsn = InvalidXLogRecPtr; + StringInfoData query; + XLogRecPtr our_lsn = InvalidXLogRecPtr; /* node_id used for logging purposes */ - int requesting_node_id = PG_GETARG_INT32(0); - int current_electoral_term = PG_GETARG_INT32(1); + int requesting_node_id = PG_GETARG_INT32(0); + int current_electoral_term = PG_GETARG_INT32(1); - int ret; - bool isnull; + int ret; + bool isnull; if (!shared_state) PG_RETURN_NULL(); @@ -299,11 +312,11 @@ request_vote(PG_FUNCTION_ARGS) initStringInfo(&query); appendStringInfo( - &query, + &query, #if (PG_VERSION_NUM >= 100000) - "SELECT pg_catalog.pg_last_wal_receive_lsn()"); + "SELECT pg_catalog.pg_last_wal_receive_lsn()"); #else - "SELECT pg_catalog.pg_last_xlog_receive_location()"); + "SELECT pg_catalog.pg_last_xlog_receive_location()"); #endif elog(DEBUG1, "query: %s", query.data); @@ -331,7 +344,7 @@ request_vote(PG_FUNCTION_ARGS) LWLockRelease(shared_state->lock); - // should we free "query" here? + /* should we free "query" here? */ SPI_finish(); PG_RETURN_LSN(our_lsn); @@ -365,7 +378,7 @@ Datum set_voting_status_initiated(PG_FUNCTION_ARGS) { #ifndef BDR_ONLY - int electoral_term; + int electoral_term; LWLockAcquire(shared_state->lock, LW_SHARED); shared_state->voting_status = VS_VOTE_INITIATED; @@ -386,8 +399,8 @@ Datum other_node_is_candidate(PG_FUNCTION_ARGS) { #ifndef BDR_ONLY - int requesting_node_id = PG_GETARG_INT32(0); - int electoral_term = PG_GETARG_INT32(1); + int requesting_node_id = PG_GETARG_INT32(0); + int electoral_term = PG_GETARG_INT32(1); if (!shared_state) PG_RETURN_NULL(); @@ -419,7 +432,7 @@ Datum notify_follow_primary(PG_FUNCTION_ARGS) { #ifndef BDR_ONLY - int primary_node_id = PG_GETARG_INT32(0); + int primary_node_id = PG_GETARG_INT32(0); if (!shared_state) PG_RETURN_NULL(); @@ -442,7 +455,7 @@ notify_follow_primary(PG_FUNCTION_ARGS) Datum get_new_primary(PG_FUNCTION_ARGS) { - int new_primary_node_id = UNKNOWN_NODE_ID; + int new_primary_node_id = UNKNOWN_NODE_ID; if (!shared_state) PG_RETURN_NULL(); @@ -481,8 +494,8 @@ reset_voting_status(PG_FUNCTION_ARGS) Datum am_bdr_failover_handler(PG_FUNCTION_ARGS) { - int node_id = PG_GETARG_INT32(0); - bool am_handler = false; + int node_id = PG_GETARG_INT32(0); + bool am_handler = false; if (!shared_state) PG_RETURN_NULL(); diff --git a/repmgr.h b/repmgr.h index 1192863d..5b5ec855 100644 --- a/repmgr.h +++ b/repmgr.h @@ -60,17 +60,17 @@ */ #define DEFAULT_LOCATION "default" #define DEFAULT_PRIORITY 100 -#define DEFAULT_RECONNECTION_ATTEMPTS 6 /* seconds */ -#define DEFAULT_RECONNECTION_INTERVAL 10 /* seconds */ -#define DEFAULT_MONITORING_INTERVAL 2 /* seconds */ -#define DEFAULT_ASYNC_QUERY_TIMEOUT 60 /* seconds */ -#define DEFAULT_PRIMARY_NOTIFICATION_TIMEOUT 60 /* seconds */ -#define DEFAULT_PRIMARY_FOLLOW_TIMEOUT 60 /* seconds */ -#define DEFAULT_BDR_RECOVERY_TIMEOUT 30 /* seconds */ -#define DEFAULT_ARCHIVE_READY_WARNING 16 /* WAL files */ -#define DEFAULT_ARCHIVE_READY_CRITICAL 128 /* WAL files */ -#define DEFAULT_REPLICATION_LAG_WARNING 300 /* seconds */ -#define DEFAULT_REPLICATION_LAG_CRITICAL 600 /* seconds */ +#define DEFAULT_RECONNECTION_ATTEMPTS 6 /* seconds */ +#define DEFAULT_RECONNECTION_INTERVAL 10 /* seconds */ +#define DEFAULT_MONITORING_INTERVAL 2 /* seconds */ +#define DEFAULT_ASYNC_QUERY_TIMEOUT 60 /* seconds */ +#define DEFAULT_PRIMARY_NOTIFICATION_TIMEOUT 60 /* seconds */ +#define DEFAULT_PRIMARY_FOLLOW_TIMEOUT 60 /* seconds */ +#define DEFAULT_BDR_RECOVERY_TIMEOUT 30 /* seconds */ +#define DEFAULT_ARCHIVE_READY_WARNING 16 /* WAL files */ +#define DEFAULT_ARCHIVE_READY_CRITICAL 128 /* WAL files */ +#define DEFAULT_REPLICATION_LAG_WARNING 300 /* seconds */ +#define DEFAULT_REPLICATION_LAG_CRITICAL 600 /* seconds */ #ifndef RECOVERY_COMMAND_FILE @@ -83,4 +83,4 @@ -#endif /* _REPMGR_H_ */ +#endif /* _REPMGR_H_ */ diff --git a/repmgrd-bdr.c b/repmgrd-bdr.c index 96a14617..b17c702d 100644 --- a/repmgrd-bdr.c +++ b/repmgrd-bdr.c @@ -39,9 +39,9 @@ do_bdr_node_check(void) void monitor_bdr(void) { - NodeInfoList nodes = T_NODE_INFO_LIST_INITIALIZER; + NodeInfoList nodes = T_NODE_INFO_LIST_INITIALIZER; t_bdr_node_info bdr_node_info = T_BDR_NODE_INFO_INITIALIZER; - RecordStatus record_status; + RecordStatus record_status; NodeInfoListCell *cell; PQExpBufferData event_details; instr_time log_status_interval_start; @@ -65,8 +65,7 @@ monitor_bdr(void) } /* - * Verify that database is a BDR one - * TODO: check if supported BDR version? + * Verify that database is a BDR one TODO: check if supported BDR version? */ log_info(_("connected to database, checking for BDR")); @@ -81,7 +80,10 @@ monitor_bdr(void) log_error(_("repmgr metadata table 'repmgr.%s' is not in the 'repmgr' replication set"), "nodes"); - /* TODO: add `repmgr bdr sync` or similar for this situation, and hint here */ + /* + * TODO: add `repmgr bdr sync` or similar for this situation, and hint + * here + */ exit(ERR_BAD_CONFIG); } @@ -100,8 +102,8 @@ monitor_bdr(void) record_status = get_node_record(local_conn, config_file_options.node_id, &local_node_info); /* - * Terminate if we can't find the local node record. This is a "fix-the-config" - * situation, not a lot else we can do. + * Terminate if we can't find the local node record. This is a + * "fix-the-config" situation, not a lot else we can do. */ if (record_status != RECORD_FOUND) { @@ -139,7 +141,8 @@ monitor_bdr(void) NULL); /* - * retrieve list of all nodes - we'll need these if the DB connection goes away + * retrieve list of all nodes - we'll need these if the DB connection goes + * away */ get_all_node_records(local_conn, &nodes); @@ -184,80 +187,81 @@ monitor_bdr(void) switch (cell->node_info->monitoring_state) { case MS_NORMAL: - { - if (is_server_available(cell->node_info->conninfo) == false) { - /* node is down, we were expecting it to be up */ - if (cell->node_info->node_status == NODE_STATUS_UP) + if (is_server_available(cell->node_info->conninfo) == false) { - instr_time node_unreachable_start; - INSTR_TIME_SET_CURRENT(node_unreachable_start); - - cell->node_info->node_status = NODE_STATUS_DOWN; - - if (cell->node_info->conn != NULL) - { - PQfinish(cell->node_info->conn); - cell->node_info->conn = NULL; - } - - log_warning(_("unable to connect to node %s (ID %i)"), - cell->node_info->node_name, cell->node_info->node_id); - cell->node_info->conn = try_reconnect(cell->node_info); - - /* node has recovered - log and continue */ + /* node is down, we were expecting it to be up */ if (cell->node_info->node_status == NODE_STATUS_UP) { - int node_unreachable_elapsed = calculate_elapsed(node_unreachable_start); + instr_time node_unreachable_start; - initPQExpBuffer(&event_details); + INSTR_TIME_SET_CURRENT(node_unreachable_start); - appendPQExpBuffer(&event_details, - _("reconnected to node %i after %i seconds"), - cell->node_info->node_id, - node_unreachable_elapsed); - log_notice("%s", event_details.data); + cell->node_info->node_status = NODE_STATUS_DOWN; - create_event_notification(cell->node_info->conn, - &config_file_options, - config_file_options.node_id, - "bdr_reconnect", - true, - event_details.data); - termPQExpBuffer(&event_details); + if (cell->node_info->conn != NULL) + { + PQfinish(cell->node_info->conn); + cell->node_info->conn = NULL; + } - goto loop; - } + log_warning(_("unable to connect to node %s (ID %i)"), + cell->node_info->node_name, cell->node_info->node_id); + cell->node_info->conn = try_reconnect(cell->node_info); - /* still down after reconnect attempt(s) */ - if (cell->node_info->node_status == NODE_STATUS_DOWN) - { - do_bdr_failover(&nodes, cell->node_info); - goto loop; + /* node has recovered - log and continue */ + if (cell->node_info->node_status == NODE_STATUS_UP) + { + int node_unreachable_elapsed = calculate_elapsed(node_unreachable_start); + + initPQExpBuffer(&event_details); + + appendPQExpBuffer(&event_details, + _("reconnected to node %i after %i seconds"), + cell->node_info->node_id, + node_unreachable_elapsed); + log_notice("%s", event_details.data); + + create_event_notification(cell->node_info->conn, + &config_file_options, + config_file_options.node_id, + "bdr_reconnect", + true, + event_details.data); + termPQExpBuffer(&event_details); + + goto loop; + } + + /* still down after reconnect attempt(s) */ + if (cell->node_info->node_status == NODE_STATUS_DOWN) + { + do_bdr_failover(&nodes, cell->node_info); + goto loop; + } } } } - } - break; + break; case MS_DEGRADED: - { - /* degraded monitoring */ - if (is_server_available(cell->node_info->conninfo) == true) { - do_bdr_recovery(&nodes, cell->node_info); - } + /* degraded monitoring */ + if (is_server_available(cell->node_info->conninfo) == true) + { + do_bdr_recovery(&nodes, cell->node_info); + } - } - break; + } + break; } } - loop: +loop: /* emit "still alive" log message at regular intervals, if requested */ if (config_file_options.log_status_interval > 0) { - int log_status_interval_elapsed = calculate_elapsed(log_status_interval_start); + int log_status_interval_elapsed = calculate_elapsed(log_status_interval_start); if (log_status_interval_elapsed >= config_file_options.log_status_interval) { @@ -270,9 +274,9 @@ monitor_bdr(void) if (cell->node_info->monitoring_state == MS_DEGRADED) { log_detail( - _("monitoring node \"%s\" (ID: %i) in degraded mode"), - cell->node_info->node_name, - cell->node_info->node_id); + _("monitoring node \"%s\" (ID: %i) in degraded mode"), + cell->node_info->node_name, + cell->node_info->node_id); } } INSTR_TIME_SET_CURRENT(log_status_interval_start); @@ -282,8 +286,7 @@ monitor_bdr(void) if (got_SIGHUP) { /* - * if we can reload, then could need to change - * local_conn + * if we can reload, then could need to change local_conn */ if (reload_config(&config_file_options)) { @@ -350,8 +353,8 @@ do_bdr_failover(NodeInfoList *nodes, t_node_info *monitored_node) NodeInfoListCell *cell; PQExpBufferData event_details; t_event_info event_info = T_EVENT_INFO_INITIALIZER; - t_node_info target_node = T_NODE_INFO_INITIALIZER; - t_node_info failed_node = T_NODE_INFO_INITIALIZER; + t_node_info target_node = T_NODE_INFO_INITIALIZER; + t_node_info failed_node = T_NODE_INFO_INITIALIZER; RecordStatus record_status; /* if one of the two nodes is down, cluster will be in a degraded state */ @@ -372,7 +375,10 @@ do_bdr_failover(NodeInfoList *nodes, t_node_info *monitored_node) { log_debug("do_bdr_failover() %s", cell->node_info->node_name); - /* don't attempt to connect to the current monitored node, as that's the one which has failed */ + /* + * don't attempt to connect to the current monitored node, as that's + * the one which has failed + */ if (cell->node_info->node_id == monitored_node->node_id) continue; @@ -459,21 +465,21 @@ do_bdr_failover(NodeInfoList *nodes, t_node_info *monitored_node) /* * Create an event record * - * If we were able to connect to another node, we'll update the - * event log there. + * If we were able to connect to another node, we'll update the event log + * there. * - * In any case the event notification command will be triggered - * with the event "bdr_failover" + * In any case the event notification command will be triggered with the + * event "bdr_failover" */ create_event_notification_extended( - next_node_conn, - &config_file_options, - monitored_node->node_id, - "bdr_failover", - true, - event_details.data, - &event_info); + next_node_conn, + &config_file_options, + monitored_node->node_id, + "bdr_failover", + true, + event_details.data, + &event_info); log_info("%s", event_details.data); @@ -490,15 +496,15 @@ do_bdr_failover(NodeInfoList *nodes, t_node_info *monitored_node) static void do_bdr_recovery(NodeInfoList *nodes, t_node_info *monitored_node) { - PGconn *recovered_node_conn; + PGconn *recovered_node_conn; PQExpBufferData event_details; t_event_info event_info = T_EVENT_INFO_INITIALIZER; - int i; - bool slot_reactivated = false; - int node_recovery_elapsed; + int i; + bool slot_reactivated = false; + int node_recovery_elapsed; - char node_name[MAXLEN] = ""; + char node_name[MAXLEN] = ""; log_debug("handling recovery for monitored node %i", monitored_node->node_id); @@ -519,7 +525,7 @@ do_bdr_recovery(NodeInfoList *nodes, t_node_info *monitored_node) /* * still unable to connect - the local node is probably down, so we can't * check for reconnection - */ + */ if (PQstatus(local_conn) != CONNECTION_OK) { local_conn = NULL; @@ -532,11 +538,11 @@ do_bdr_recovery(NodeInfoList *nodes, t_node_info *monitored_node) monitored_node->node_status = NODE_STATUS_UP; appendPQExpBuffer( - &event_details, - _("node \"%s\" (ID: %i) has become available after %i seconds"), - monitored_node->node_name, - monitored_node->node_id, - node_recovery_elapsed); + &event_details, + _("node \"%s\" (ID: %i) has become available after %i seconds"), + monitored_node->node_name, + monitored_node->node_id, + node_recovery_elapsed); log_notice("%s", event_details.data); @@ -560,8 +566,8 @@ do_bdr_recovery(NodeInfoList *nodes, t_node_info *monitored_node) log_debug("checking for state of replication slot for node \"%s\"", node_name); slot_status = get_bdr_node_replication_slot_status( - local_conn, - node_name); + local_conn, + node_name); if (slot_status == SLOT_ACTIVE) { @@ -621,13 +627,13 @@ do_bdr_recovery(NodeInfoList *nodes, t_node_info *monitored_node) event_info.node_name = monitored_node->node_name; create_event_notification_extended( - local_conn, - &config_file_options, - config_file_options.node_id, - "bdr_recovery", - true, - event_details.data, - &event_info); + local_conn, + &config_file_options, + config_file_options.node_id, + "bdr_recovery", + true, + event_details.data, + &event_info); } diff --git a/repmgrd-bdr.h b/repmgrd-bdr.h index f6aed76c..c891fc83 100644 --- a/repmgrd-bdr.h +++ b/repmgrd-bdr.h @@ -22,4 +22,4 @@ extern void do_bdr_node_check(void); extern void monitor_bdr(void); -#endif /* _REPMGRD_BDR_H_ */ +#endif /* _REPMGRD_BDR_H_ */ diff --git a/repmgrd-physical.c b/repmgrd-physical.c index 23a7d5ba..cf3e28ce 100644 --- a/repmgrd-physical.c +++ b/repmgrd-physical.c @@ -24,7 +24,8 @@ #include "repmgrd-physical.h" -typedef enum { +typedef enum +{ FAILOVER_STATE_UNKNOWN = -1, FAILOVER_STATE_NONE, FAILOVER_STATE_PROMOTED, @@ -41,7 +42,8 @@ typedef enum { } FailoverState; -typedef enum { +typedef enum +{ ELECTION_NOT_CANDIDATE = -1, ELECTION_WON, ELECTION_LOST, @@ -55,7 +57,7 @@ static PGconn *primary_conn = NULL; #ifndef BDR_ONLY static FailoverState failover_state = FAILOVER_STATE_UNKNOWN; -static int primary_node_id = UNKNOWN_NODE_ID; +static int primary_node_id = UNKNOWN_NODE_ID; static t_node_info upstream_node_info = T_NODE_INFO_INITIALIZER; static NodeInfoList standby_nodes = T_NODE_INFO_LIST_INITIALIZER; @@ -75,7 +77,7 @@ static bool wait_primary_notification(int *new_primary_id); static FailoverState follow_new_primary(int new_primary_id); static void reset_node_voting_status(void); -void close_connections_physical(); +void close_connections_physical(); static bool do_primary_failover(void); static bool do_upstream_standby_failover(void); @@ -90,37 +92,37 @@ void do_physical_node_check(void) { #ifndef BDR_ONLY - /* - * Check if node record is active - if not, and `failover=automatic`, the node - * won't be considered as a promotion candidate; this often happens when - * a failed primary is recloned and the node was not re-registered, giving - * the impression failover capability is there when it's not. In this case - * abort with an error and a hint about registering. - * - * If `failover=manual`, repmgrd can continue to passively monitor the node, but - * we should nevertheless issue a warning and the same hint. - */ + /* + * Check if node record is active - if not, and `failover=automatic`, the + * node won't be considered as a promotion candidate; this often happens + * when a failed primary is recloned and the node was not re-registered, + * giving the impression failover capability is there when it's not. In + * this case abort with an error and a hint about registering. + * + * If `failover=manual`, repmgrd can continue to passively monitor the + * node, but we should nevertheless issue a warning and the same hint. + */ - if (local_node_info.active == false) - { - char *hint = "Check that 'repmgr (primary|standby) register' was executed for this node"; + if (local_node_info.active == false) + { + char *hint = "Check that 'repmgr (primary|standby) register' was executed for this node"; - switch (config_file_options.failover) - { - /* "failover" is an enum, all values should be covered here */ + switch (config_file_options.failover) + { + /* "failover" is an enum, all values should be covered here */ - case FAILOVER_AUTOMATIC: - log_error(_("this node is marked as inactive and cannot be used as a failover target")); - log_hint(_("%s"), hint); + case FAILOVER_AUTOMATIC: + log_error(_("this node is marked as inactive and cannot be used as a failover target")); + log_hint(_("%s"), hint); PQfinish(local_conn); - terminate(ERR_BAD_CONFIG); + terminate(ERR_BAD_CONFIG); - case FAILOVER_MANUAL: - log_warning(_("this node is marked as inactive and will be passively monitored only")); - log_hint(_("%s"), hint); - break; - } - } + case FAILOVER_MANUAL: + log_warning(_("this node is marked as inactive and will be passively monitored only")); + log_hint(_("%s"), hint); + break; + } + } if (config_file_options.failover == FAILOVER_AUTOMATIC) { @@ -129,7 +131,7 @@ do_physical_node_check(void) * won't be able to perform any useful action */ - bool required_param_missing = false; + bool required_param_missing = false; if (config_file_options.promote_command[0] == '\0') { @@ -138,8 +140,8 @@ do_physical_node_check(void) if (config_file_options.service_promote_command[0] != '\0') { /* - * if repmgrd executes "service_promote_command" directly, repmgr metadata - * won't get updated + * if repmgrd executes "service_promote_command" directly, + * repmgr metadata won't get updated */ log_hint(_("\"service_promote_command\" is set, but can only be executed by \"repmgr standby promote\"")); } @@ -242,8 +244,8 @@ monitor_streaming_primary(void) PQfinish(local_conn); /* - * as we're monitoring the primary, no point in trying to write - * the event to the database + * as we're monitoring the primary, no point in trying to + * write the event to the database * * XXX possible pre-action event */ @@ -260,7 +262,7 @@ monitor_streaming_primary(void) if (local_node_info.node_status == NODE_STATUS_UP) { - int local_node_unreachable_elapsed = calculate_elapsed(local_node_unreachable_start); + int local_node_unreachable_elapsed = calculate_elapsed(local_node_unreachable_start); initPQExpBuffer(&event_details); @@ -270,11 +272,11 @@ monitor_streaming_primary(void) log_notice("%s", event_details.data); create_event_notification(local_conn, - &config_file_options, - config_file_options.node_id, - "repmgrd_local_reconnect", - true, - event_details.data); + &config_file_options, + config_file_options.node_id, + "repmgrd_local_reconnect", + true, + event_details.data); termPQExpBuffer(&event_details); goto loop; @@ -289,7 +291,7 @@ monitor_streaming_primary(void) if (monitoring_state == MS_DEGRADED) { - int degraded_monitoring_elapsed = calculate_elapsed(degraded_monitoring_start); + int degraded_monitoring_elapsed = calculate_elapsed(degraded_monitoring_start); if (config_file_options.degraded_monitoring_timeout > 0 && degraded_monitoring_elapsed > config_file_options.degraded_monitoring_timeout) @@ -346,16 +348,16 @@ monitor_streaming_primary(void) /* - * possibly attempt to find another node from cached list - * check if there's a new primary - if so add hook for fencing? - * loop, if starts up check status, switch monitoring mode + * possibly attempt to find another node from cached list check if + * there's a new primary - if so add hook for fencing? loop, if + * starts up check status, switch monitoring mode */ } - loop: +loop: /* emit "still alive" log message at regular intervals, if requested */ if (config_file_options.log_status_interval > 0) { - int log_status_interval_elapsed = calculate_elapsed(log_status_interval_start); + int log_status_interval_elapsed = calculate_elapsed(log_status_interval_start); if (log_status_interval_elapsed >= config_file_options.log_status_interval) { @@ -421,9 +423,9 @@ monitor_streaming_standby(void) log_debug("monitor_streaming_standby()"); /* - * If no upstream node id is specified in the metadata, we'll try - * and determine the current cluster primary in the assumption we - * should connect to that by default. + * If no upstream node id is specified in the metadata, we'll try and + * determine the current cluster primary in the assumption we should + * connect to that by default. */ if (local_node_info.upstream_node_id == UNKNOWN_NODE_ID) { @@ -431,9 +433,9 @@ monitor_streaming_standby(void) /* * Terminate if there doesn't appear to be an active cluster primary. - * There could be one or more nodes marked as inactive primaries, and one - * of them could actually be a primary, but we can't sensibly monitor - * in that state. + * There could be one or more nodes marked as inactive primaries, and + * one of them could actually be a primary, but we can't sensibly + * monitor in that state. */ if (local_node_info.upstream_node_id == NODE_NOT_FOUND) { @@ -446,14 +448,14 @@ monitor_streaming_standby(void) record_status = get_node_record(local_conn, local_node_info.upstream_node_id, &upstream_node_info); /* - * Terminate if we can't find the record for the node we're supposed - * to monitor. This is a "fix-the-config" situation, not a lot else we - * can do. + * Terminate if we can't find the record for the node we're supposed to + * monitor. This is a "fix-the-config" situation, not a lot else we can + * do. */ if (record_status == RECORD_NOT_FOUND) { log_error(_("no record found for upstream node (ID: %i), terminating"), - local_node_info.upstream_node_id); + local_node_info.upstream_node_id); log_hint(_("ensure the upstream node is registered correctly")); PQfinish(local_conn); exit(ERR_DB_CONN); @@ -461,7 +463,7 @@ monitor_streaming_standby(void) else if (record_status == RECORD_ERROR) { log_error(_("unable to retrieve record for upstream node (ID: %i), terminating"), - local_node_info.upstream_node_id); + local_node_info.upstream_node_id); PQfinish(local_conn); exit(ERR_DB_CONN); } @@ -473,8 +475,8 @@ monitor_streaming_standby(void) /* * Upstream node must be running at repmgrd startup. * - * We could possibly have repmgrd skip to degraded monitoring mode until it - * comes up, but there doesn't seem to be much point in doing that. + * We could possibly have repmgrd skip to degraded monitoring mode until + * it comes up, but there doesn't seem to be much point in doing that. */ if (PQstatus(upstream_conn) != CONNECTION_OK) { @@ -486,15 +488,18 @@ monitor_streaming_standby(void) exit(ERR_DB_CONN); } - /* refresh upstream node record from upstream node, so it's as up-to-date as possible */ + /* + * refresh upstream node record from upstream node, so it's as up-to-date + * as possible + */ record_status = get_node_record(upstream_conn, upstream_node_info.node_id, &upstream_node_info); if (upstream_node_info.type == STANDBY) { /* - * Currently cascaded standbys need to be able to connect to the primary. - * We could possibly add a limited connection mode for cases where this isn't - * possible. + * Currently cascaded standbys need to be able to connect to the + * primary. We could possibly add a limited connection mode for cases + * where this isn't possible. */ primary_conn = establish_primary_db_connection(upstream_conn, false); @@ -518,6 +523,7 @@ monitor_streaming_standby(void) if (startup_event_logged == false) { PQExpBufferData event_details; + initPQExpBuffer(&event_details); appendPQExpBuffer(&event_details, @@ -583,7 +589,7 @@ monitor_streaming_standby(void) /* Node has recovered - log and continue */ if (upstream_node_info.node_status == NODE_STATUS_UP) { - int upstream_node_unreachable_elapsed = calculate_elapsed(upstream_node_unreachable_start); + int upstream_node_unreachable_elapsed = calculate_elapsed(upstream_node_unreachable_start); initPQExpBuffer(&event_details); @@ -606,7 +612,7 @@ monitor_streaming_standby(void) /* still down after reconnect attempt(s) */ if (upstream_node_info.node_status == NODE_STATUS_DOWN) { - bool failover_done = false; + bool failover_done = false; if (upstream_node_info.type == PRIMARY) { @@ -617,7 +623,10 @@ monitor_streaming_standby(void) failover_done = do_upstream_standby_failover(); } - /* XXX it's possible it will make sense to return in all cases to restart monitoring */ + /* + * XXX it's possible it will make sense to return in all + * cases to restart monitoring + */ if (failover_done == true) { primary_node_id = get_primary_node_id(local_conn); @@ -629,7 +638,7 @@ monitor_streaming_standby(void) if (monitoring_state == MS_DEGRADED) { - int degraded_monitoring_elapsed = calculate_elapsed(degraded_monitoring_start); + int degraded_monitoring_elapsed = calculate_elapsed(degraded_monitoring_start); log_debug("monitoring node %i in degraded state for %i seconds", upstream_node_info.node_id, @@ -641,10 +650,13 @@ monitor_streaming_standby(void) if (PQstatus(upstream_conn) == CONNECTION_OK) { - // XXX check here if upstream is still primary - // -> will be a problem if another node was promoted in the meantime - // and upstream is now former primary - // XXX scan other nodes to see if any has become primary + /* XXX check here if upstream is still primary */ + /* + * -> will be a problem if another node was promoted in + * the meantime + */ + /* and upstream is now former primary */ + /* XXX scan other nodes to see if any has become primary */ upstream_node_info.node_status = NODE_STATUS_UP; monitoring_state = MS_NORMAL; @@ -684,12 +696,12 @@ monitor_streaming_standby(void) else { /* - * unable to connect to former primary - check if another node has - * been promoted + * unable to connect to former primary - check if another node + * has been promoted */ NodeInfoListCell *cell; - int follow_node_id = UNKNOWN_NODE_ID; + int follow_node_id = UNKNOWN_NODE_ID; /* local node has been promoted */ if (get_recovery_type(local_conn) == RECTYPE_PRIMARY) @@ -697,12 +709,13 @@ monitor_streaming_standby(void) log_notice(_("local node is primary, checking local node record")); /* - * There may be a delay between the node being promoted and the local - * record being updated, so if the node record still shows it as a - * standby, do nothing, we'll catch the update during the next loop. - * (e.g. node was manually - * promoted) we'll do nothing, as the repmgr metadata is now out-of-sync. - * If it does get fixed, we'll catch it here on a future iteration. + * There may be a delay between the node being promoted + * and the local record being updated, so if the node + * record still shows it as a standby, do nothing, we'll + * catch the update during the next loop. (e.g. node was + * manually promoted) we'll do nothing, as the repmgr + * metadata is now out-of-sync. If it does get fixed, + * we'll catch it here on a future iteration. */ /* refresh own internal node record */ @@ -710,7 +723,7 @@ monitor_streaming_standby(void) if (local_node_info.type == PRIMARY) { - int degraded_monitoring_elapsed = calculate_elapsed(degraded_monitoring_start); + int degraded_monitoring_elapsed = calculate_elapsed(degraded_monitoring_start); log_notice(_("resuming monitoring as primary node after %i seconds"), degraded_monitoring_elapsed); @@ -769,32 +782,33 @@ monitor_streaming_standby(void) } } - loop: +loop: /* emit "still alive" log message at regular intervals, if requested */ if (config_file_options.log_status_interval > 0) { - int log_status_interval_elapsed = calculate_elapsed(log_status_interval_start); + int log_status_interval_elapsed = calculate_elapsed(log_status_interval_start); if (log_status_interval_elapsed >= config_file_options.log_status_interval) { PQExpBufferData monitoring_summary; + initPQExpBuffer(&monitoring_summary); appendPQExpBuffer( - &monitoring_summary, - _("node \"%s\" (node ID: %i) monitoring upstream node \"%s\" (node ID: %i) in %s state"), - local_node_info.node_name, - local_node_info.node_id, - upstream_node_info.node_name, - upstream_node_info.node_id, - print_monitoring_state(monitoring_state)); + &monitoring_summary, + _("node \"%s\" (node ID: %i) monitoring upstream node \"%s\" (node ID: %i) in %s state"), + local_node_info.node_name, + local_node_info.node_id, + upstream_node_info.node_name, + upstream_node_info.node_id, + print_monitoring_state(monitoring_state)); if (config_file_options.failover == FAILOVER_MANUAL) { appendPQExpBuffer( - &monitoring_summary, - _(" (automatic failover disabled)")); + &monitoring_summary, + _(" (automatic failover disabled)")); } log_info("%s", monitoring_summary.data); @@ -827,33 +841,35 @@ monitor_streaming_standby(void) if (update_node_record_set_active(primary_conn, local_node_info.node_id, false) == true) { PQExpBufferData event_details; + initPQExpBuffer(&event_details); local_node_info.active = false; appendPQExpBuffer( - &event_details, - _("unable to connect to local node \"%s\" (ID: %i), marking inactive"), - local_node_info.node_name, - local_node_info.node_id); + &event_details, + _("unable to connect to local node \"%s\" (ID: %i), marking inactive"), + local_node_info.node_name, + local_node_info.node_id); log_warning("%s", event_details.data) - create_event_notification( - primary_conn, - &config_file_options, - local_node_info.node_id, - "standby_failure", - false, - event_details.data); + create_event_notification( + primary_conn, + &config_file_options, + local_node_info.node_id, + "standby_failure", + false, + event_details.data); termPQExpBuffer(&event_details); } } } } - else { + else + { if (local_node_info.active == false) { if (PQstatus(primary_conn) == CONNECTION_OK) @@ -861,26 +877,27 @@ monitor_streaming_standby(void) if (update_node_record_set_active(primary_conn, local_node_info.node_id, true) == true) { PQExpBufferData event_details; + initPQExpBuffer(&event_details); local_node_info.active = true; appendPQExpBuffer( - &event_details, - _("reconnected to local node \"%s\" (ID: %i), marking active"), - local_node_info.node_name, - local_node_info.node_id); + &event_details, + _("reconnected to local node \"%s\" (ID: %i), marking active"), + local_node_info.node_name, + local_node_info.node_id); log_warning("%s", event_details.data) - create_event_notification( - primary_conn, - &config_file_options, - local_node_info.node_id, - "standby_recovery", - true, - event_details.data); + create_event_notification( + primary_conn, + &config_file_options, + local_node_info.node_id, + "standby_recovery", + true, + event_details.data); termPQExpBuffer(&event_details); } @@ -954,8 +971,8 @@ do_primary_failover(void) best_candidate = poll_best_candidate(&standby_nodes); /* - * this can occur in a tie-break situation, where this node establishes - * it is the best candidate + * this can occur in a tie-break situation, where this node + * establishes it is the best candidate */ if (best_candidate->node_id == local_node_info.node_id) { @@ -965,7 +982,7 @@ do_primary_failover(void) } else { - PGconn *candidate_conn = NULL; + PGconn *candidate_conn = NULL; log_info("node %i is the best candidate, waiting for it to confirm so I can follow it", best_candidate->node_id); @@ -978,7 +995,7 @@ do_primary_failover(void) { notify_follow_primary(candidate_conn, best_candidate->node_id); - /* we'll wait for the candidate to get back to us */ + /* we'll wait for the candidate to get back to us */ failover_state = FAILOVER_STATE_WAITING_NEW_PRIMARY; } else @@ -1012,14 +1029,14 @@ do_primary_failover(void) /* - * node has decided it is a follower, so will await notification - * from the candidate that it has promoted itself and can be followed + * node has decided it is a follower, so will await notification from the + * candidate that it has promoted itself and can be followed */ if (failover_state == FAILOVER_STATE_WAITING_NEW_PRIMARY) { - int new_primary_id; + int new_primary_id; - /* TODO: rerun election if new primary doesn't appear after timeout */ + /* TODO: rerun election if new primary doesn't appear after timeout */ /* either follow or time out; either way resume monitoring */ if (wait_primary_notification(&new_primary_id) == true) @@ -1048,7 +1065,7 @@ do_primary_failover(void) t_node_info new_primary = T_NODE_INFO_INITIALIZER; RecordStatus record_status = RECORD_NOT_FOUND; - PGconn *new_primary_conn; + PGconn *new_primary_conn; record_status = get_node_record(local_conn, new_primary_id, &new_primary); @@ -1060,6 +1077,7 @@ do_primary_failover(void) else { PQExpBufferData event_details; + initPQExpBuffer(&event_details); appendPQExpBuffer(&event_details, _("node %i is in manual failover mode and is now disconnected from streaming replication"), @@ -1068,13 +1086,17 @@ do_primary_failover(void) new_primary_conn = establish_db_connection(new_primary.conninfo, false); create_event_notification( - new_primary_conn, - &config_file_options, - local_node_info.node_id, - "standby_disconnect_manual", - /* here "true" indicates the action has occurred as expected */ - true, - event_details.data); + new_primary_conn, + &config_file_options, + local_node_info.node_id, + "standby_disconnect_manual", + + /* + * here "true" indicates the action has occurred as + * expected + */ + true, + event_details.data); PQfinish(new_primary_conn); termPQExpBuffer(&event_details); @@ -1092,7 +1114,7 @@ do_primary_failover(void) } } - switch(failover_state) + switch (failover_state) { case FAILOVER_STATE_PROMOTED: log_debug("failover state is PROMOTED"); @@ -1112,7 +1134,10 @@ do_primary_failover(void) case FAILOVER_STATE_PRIMARY_REAPPEARED: log_debug("failover state is PRIMARY_REAPPEARED"); - /* notify siblings that they should resume following the original primary */ + /* + * notify siblings that they should resume following the original + * primary + */ notify_followers(&standby_nodes, upstream_node_info.node_id); /* we no longer care about our former siblings */ @@ -1151,6 +1176,7 @@ do_primary_failover(void) return false; case FAILOVER_STATE_FOLLOW_FAIL: + /* * for whatever reason we were unable to follow the new primary - * continue monitoring in degraded state @@ -1190,8 +1216,8 @@ do_primary_failover(void) static void update_monitoring_history(void) { - ReplInfo replication_info = T_REPLINFO_INTIALIZER; - XLogRecPtr primary_last_wal_location = InvalidXLogRecPtr; + ReplInfo replication_info = T_REPLINFO_INTIALIZER; + XLogRecPtr primary_last_wal_location = InvalidXLogRecPtr; long long unsigned int apply_lag_bytes = 0; long long unsigned int replication_lag_bytes = 0; @@ -1229,11 +1255,14 @@ update_monitoring_history(void) if (primary_last_wal_location >= replication_info.last_wal_receive_lsn) { - replication_lag_bytes = (long long unsigned int)(primary_last_wal_location - replication_info.last_wal_receive_lsn); + replication_lag_bytes = (long long unsigned int) (primary_last_wal_location - replication_info.last_wal_receive_lsn); } else { - /* This should never happen, but in case it does set replication lag to zero */ + /* + * This should never happen, but in case it does set replication lag + * to zero + */ log_warning("primary xlog (%X/%X) location appears less than standby receive location (%X/%X)", format_lsn(primary_last_wal_location), format_lsn(replication_info.last_wal_receive_lsn)); @@ -1241,16 +1270,16 @@ update_monitoring_history(void) } add_monitoring_record( - primary_conn, - local_conn, - primary_node_id, - local_node_info.node_id, - replication_info.current_timestamp, - primary_last_wal_location, - replication_info.last_wal_receive_lsn, - replication_info.last_xact_replay_timestamp, - replication_lag_bytes, - apply_lag_bytes); + primary_conn, + local_conn, + primary_node_id, + local_node_info.node_id, + replication_info.current_timestamp, + primary_last_wal_location, + replication_info.last_wal_receive_lsn, + replication_info.last_xact_replay_timestamp, + replication_lag_bytes, + apply_lag_bytes); } @@ -1275,7 +1304,7 @@ do_upstream_standby_failover(void) t_node_info primary_node_info = T_NODE_INFO_INITIALIZER; RecordStatus record_status = RECORD_NOT_FOUND; RecoveryType primary_type = RECTYPE_UNKNOWN; - int r; + int r; char parsed_follow_command[MAXPGPATH] = ""; PQfinish(upstream_conn); @@ -1286,9 +1315,10 @@ do_upstream_standby_failover(void) log_error(_("unable to retrieve primary node record")); return false; } + /* - * Verify that we can still talk to the cluster primary, even though - * the node's upstream is not available + * Verify that we can still talk to the cluster primary, even though the + * node's upstream is not available */ check_connection(&primary_node_info, &primary_conn); @@ -1344,17 +1374,17 @@ do_upstream_standby_failover(void) log_error("%s", event_details.data); - /* It may not possible to write to the event notification - * table but we should be able to generate an external notification - * if required. + /* + * It may not possible to write to the event notification table but we + * should be able to generate an external notification if required. */ create_event_notification( - primary_conn, - &config_file_options, - local_node_info.node_id, - "repmgrd_failover_follow", - false, - event_details.data); + primary_conn, + &config_file_options, + local_node_info.node_id, + "repmgrd_failover_follow", + false, + event_details.data); termPQExpBuffer(&event_details); } @@ -1374,12 +1404,12 @@ do_upstream_standby_failover(void) log_error("%s", event_details.data); create_event_notification( - NULL, - &config_file_options, - local_node_info.node_id, - "repmgrd_failover_follow", - false, - event_details.data); + NULL, + &config_file_options, + local_node_info.node_id, + "repmgrd_failover_follow", + false, + event_details.data); termPQExpBuffer(&event_details); @@ -1390,8 +1420,9 @@ do_upstream_standby_failover(void) record_status = get_node_record(primary_conn, local_node_info.node_id, &local_node_info); /* - * highly improbable this will happen, but in case we're unable to retrieve - * our node record from the primary, update it ourselves, and hope for the best + * highly improbable this will happen, but in case we're unable to + * retrieve our node record from the primary, update it ourselves, and + * hope for the best */ if (record_status != RECORD_FOUND) { @@ -1406,12 +1437,12 @@ do_upstream_standby_failover(void) log_notice("%s", event_details.data); create_event_notification( - primary_conn, - &config_file_options, - local_node_info.node_id, - "repmgrd_failover_follow", - true, - event_details.data); + primary_conn, + &config_file_options, + local_node_info.node_id, + "repmgrd_failover_follow", + true, + event_details.data); termPQExpBuffer(&event_details); @@ -1425,8 +1456,8 @@ static FailoverState promote_self(void) { PQExpBufferData event_details; - char *promote_command; - int r; + char *promote_command; + int r; /* Store details of the failed node here */ t_node_info failed_primary = T_NODE_INFO_INITIALIZER; @@ -1434,8 +1465,8 @@ promote_self(void) /* * optionally add a delay before promoting the standby; this is mainly - * useful for testing (e.g. for reappearance of the original primary) - * and is not documented. + * useful for testing (e.g. for reappearance of the original primary) and + * is not documented. */ if (config_file_options.promote_delay > 0) { @@ -1467,22 +1498,22 @@ promote_self(void) r = system(promote_command); /* connection should stay up, but check just in case */ - if(PQstatus(local_conn) != CONNECTION_OK) + if (PQstatus(local_conn) != CONNECTION_OK) { local_conn = establish_db_connection(local_node_info.conninfo, true); /* assume node failed */ - if(PQstatus(local_conn) != CONNECTION_OK) + if (PQstatus(local_conn) != CONNECTION_OK) { log_error(_("unable to reconnect to local node")); - // XXX handle this + /* XXX handle this */ return FAILOVER_STATE_LOCAL_NODE_FAILURE; } } if (r != 0) { - int primary_node_id; + int primary_node_id; upstream_conn = get_primary_connection(local_conn, &primary_node_id, NULL); @@ -1499,18 +1530,18 @@ promote_self(void) failed_primary.node_id); create_event_notification(upstream_conn, - &config_file_options, - local_node_info.node_id, - "repmgrd_failover_abort", - true, - event_details.data); + &config_file_options, + local_node_info.node_id, + "repmgrd_failover_abort", + true, + event_details.data); termPQExpBuffer(&event_details); - //primary_conn = NULL; + /* primary_conn = NULL; */ - // XXX handle this! - // -> we'll need to let the other nodes know too.... + /* XXX handle this! */ + /* -> we'll need to let the other nodes know too.... */ /* no failover occurred but we'll want to restart connections */ return FAILOVER_STATE_PRIMARY_REAPPEARED; @@ -1521,12 +1552,12 @@ promote_self(void) initPQExpBuffer(&event_details); create_event_notification( - NULL, - &config_file_options, - local_node_info.node_id, - "repmgrd_promote_error", - true, - event_details.data); + NULL, + &config_file_options, + local_node_info.node_id, + "repmgrd_promote_error", + true, + event_details.data); termPQExpBuffer(&event_details); return FAILOVER_STATE_PROMOTION_FAILED; @@ -1548,11 +1579,11 @@ promote_self(void) /* local_conn is now the primary connection */ create_event_notification(local_conn, - &config_file_options, - local_node_info.node_id, - "repmgrd_failover_promote", - true, - event_details.data); + &config_file_options, + local_node_info.node_id, + "repmgrd_failover_promote", + true, + event_details.data); termPQExpBuffer(&event_details); @@ -1610,8 +1641,7 @@ poll_best_candidate(NodeInfoList *standby_nodes) * cases we could end up with two candidate nodes, so they should each * come to the same conclusion. * - * XXX check there are no cases where the standby node's LSN is - * not set + * XXX check there are no cases where the standby node's LSN is not set */ for (cell = standby_nodes->head; cell; cell = cell->next) { @@ -1653,7 +1683,7 @@ poll_best_candidate(NodeInfoList *standby_nodes) static bool wait_primary_notification(int *new_primary_id) { - int i; + int i; for (i = 0; i < config_file_options.primary_notification_timeout; i++) { @@ -1683,13 +1713,13 @@ follow_new_primary(int new_primary_id) char parsed_follow_command[MAXPGPATH] = ""; PQExpBufferData event_details; - int r; + int r; /* Store details of the failed node here */ t_node_info failed_primary = T_NODE_INFO_INITIALIZER; t_node_info new_primary = T_NODE_INFO_INITIALIZER; RecordStatus record_status = RECORD_NOT_FOUND; - bool new_primary_ok = false; + bool new_primary_ok = false; record_status = get_node_record(local_conn, new_primary_id, &new_primary); @@ -1705,11 +1735,11 @@ follow_new_primary(int new_primary_id) if (record_status != RECORD_FOUND) { log_error(_("unable to retrieve metadata record for failed primary (ID: %i)"), - local_node_info.upstream_node_id); + local_node_info.upstream_node_id); return FAILOVER_STATE_FOLLOW_FAIL; } - // XXX check if new_primary_id == failed_primary.node_id? + /* XXX check if new_primary_id == failed_primary.node_id? */ if (log_type == REPMGR_STDERR && *config_file_options.log_file) { @@ -1721,6 +1751,7 @@ follow_new_primary(int new_primary_id) if (PQstatus(upstream_conn) == CONNECTION_OK) { RecoveryType primary_recovery_type = get_recovery_type(upstream_conn); + if (primary_recovery_type == RECTYPE_PRIMARY) { new_primary_ok = true; @@ -1739,8 +1770,8 @@ follow_new_primary(int new_primary_id) } /* - * disconnect from local node, as follow operation will result in - * a server restart + * disconnect from local node, as follow operation will result in a server + * restart */ PQfinish(local_conn); @@ -1761,25 +1792,28 @@ follow_new_primary(int new_primary_id) if (r != 0) { - PGconn *old_primary_conn; + PGconn *old_primary_conn; + /* - * The follow action could still fail due to the original primary reappearing - * before the candidate could promote itself ("repmgr standby follow" will - * refuse to promote another node if the primary is available). However - * the new primary will only instruct use to follow it after it's successfully - * promoted itself, so that very likely won't be the reason for the failure. + * The follow action could still fail due to the original primary + * reappearing before the candidate could promote itself ("repmgr + * standby follow" will refuse to promote another node if the primary + * is available). However the new primary will only instruct use to + * follow it after it's successfully promoted itself, so that very + * likely won't be the reason for the failure. * * * TODO: check the new primary too - we could have a split-brain - * situation where the old primary reappeared just after the new - * one promoted itself. + * situation where the old primary reappeared just after the new one + * promoted itself. */ old_primary_conn = establish_db_connection(failed_primary.conninfo, false); if (PQstatus(old_primary_conn) == CONNECTION_OK) { - // XXX add event notifications + /* XXX add event notifications */ RecoveryType upstream_recovery_type = get_recovery_type(old_primary_conn); + PQfinish(old_primary_conn); if (upstream_recovery_type == RECTYPE_PRIMARY) @@ -1826,12 +1860,12 @@ follow_new_primary(int new_primary_id) log_notice("%s", event_details.data); create_event_notification( - upstream_conn, - &config_file_options, - local_node_info.node_id, - "repmgrd_failover_follow", - true, - event_details.data); + upstream_conn, + &config_file_options, + local_node_info.node_id, + "repmgrd_failover_follow", + true, + event_details.data); termPQExpBuffer(&event_details); @@ -1842,7 +1876,7 @@ follow_new_primary(int new_primary_id) static const char * _print_voting_status(NodeVotingStatus voting_status) { - switch(voting_status) + switch (voting_status) { case VS_NO_VOTE: return "NO VOTE"; @@ -1863,7 +1897,7 @@ _print_voting_status(NodeVotingStatus voting_status) static const char * _print_election_result(ElectionResult result) { - switch(result) + switch (result) { case ELECTION_NOT_CANDIDATE: return "NOT CANDIDATE"; @@ -1890,35 +1924,35 @@ _print_election_result(ElectionResult result) static ElectionResult do_election(void) { - int electoral_term = -1; + int electoral_term = -1; - int votes_for_me = 0; + int votes_for_me = 0; /* we're visible */ - int visible_nodes = 1; + int visible_nodes = 1; /* - * get voting status from shared memory - should be one of "VS_NO_VOTE" - * or "VS_VOTE_REQUEST_RECEIVED". If VS_NO_VOTE, we declare ourselves as + * get voting status from shared memory - should be one of "VS_NO_VOTE" or + * "VS_VOTE_REQUEST_RECEIVED". If VS_NO_VOTE, we declare ourselves as * candidate and initiate the voting process. */ NodeVotingStatus voting_status; NodeInfoListCell *cell; - bool other_node_is_candidate = false; - bool other_node_is_ahead = false; + bool other_node_is_candidate = false; + bool other_node_is_ahead = false; /* - * Check if at least one server in the primary's location is visible; - * if not we'll assume a network split between this node and the primary + * Check if at least one server in the primary's location is visible; if + * not we'll assume a network split between this node and the primary * location, and not promote any standby. * - * NOTE: this function is only ever called by standbys attached to the current - * (unreachable) primary, so "upstream_node_info" will always contain the - * primary node record. + * NOTE: this function is only ever called by standbys attached to the + * current (unreachable) primary, so "upstream_node_info" will always + * contain the primary node record. */ - bool primary_location_seen = false; + bool primary_location_seen = false; /* * sleep for a random period of 100 ~ 350 ms @@ -1968,10 +2002,10 @@ do_election(void) } /* - * Here we mark ourselves as candidate, so any further vote requests - * are rejected. However it's possible another node has done the - * same thing, so when announcing ourselves as candidate to the other - * nodes, we'll check for that and withdraw our candidature. + * Here we mark ourselves as candidate, so any further vote requests are + * rejected. However it's possible another node has done the same thing, + * so when announcing ourselves as candidate to the other nodes, we'll + * check for that and withdraw our candidature. */ electoral_term = set_voting_status_initiated(local_conn); @@ -2007,20 +2041,22 @@ do_election(void) } /* - * tell the other node we're candidate - if the node has already declared - * itself, we withdraw + * tell the other node we're candidate - if the node has already + * declared itself, we withdraw * - * XXX check for situations where more than one node could end up as candidate? + * XXX check for situations where more than one node could end up as + * candidate? * - * XXX note it's possible some nodes accepted our candidature before we - * found out about the other candidate, check what happens in that situation - * -> other node will have info from all the nodes, even if not the vote, - * so it should be able to determine the best node anyway + * XXX note it's possible some nodes accepted our candidature before + * we found out about the other candidate, check what happens in that + * situation -> other node will have info from all the nodes, even if + * not the vote, so it should be able to determine the best node + * anyway */ if (announce_candidature(cell->node_info->conn, &local_node_info, cell->node_info, electoral_term) == false) { - log_debug("node %i is candidate", cell->node_info->node_id); + log_debug("node %i is candidate", cell->node_info->node_id); other_node_is_candidate = true; /* don't notify any further standbys */ @@ -2028,8 +2064,8 @@ do_election(void) } /* - * see if the node is in the primary's location (but skip the check - * if we've seen + * see if the node is in the primary's location (but skip the check if + * we've seen */ if (primary_location_seen == false) { @@ -2040,7 +2076,7 @@ do_election(void) } cell->node_info->node_status = NODE_STATUS_UP; - visible_nodes ++; + visible_nodes++; } if (other_node_is_candidate == true) @@ -2181,7 +2217,7 @@ check_connection(t_node_info *node_info, PGconn **conn) } -#endif /* #ifndef BDR_ONLY */ +#endif /* #ifndef BDR_ONLY */ void close_connections_physical() diff --git a/repmgrd-physical.h b/repmgrd-physical.h index 9d1e0c3b..2eac428a 100644 --- a/repmgrd-physical.h +++ b/repmgrd-physical.h @@ -19,10 +19,10 @@ #ifndef _REPMGRD_PHYSICAL_H_ #define _REPMGRD_PHYSICAL_H_ -void do_physical_node_check(void); +void do_physical_node_check(void); -void monitor_streaming_primary(void); -void monitor_streaming_standby(void); -void close_connections_physical(void); +void monitor_streaming_primary(void); +void monitor_streaming_standby(void); +void close_connections_physical(void); -#endif /* _REPMGRD_PHYSICAL_H_ */ +#endif /* _REPMGRD_PHYSICAL_H_ */ diff --git a/repmgrd.c b/repmgrd.c index e8d26704..914767f5 100644 --- a/repmgrd.c +++ b/repmgrd.c @@ -33,10 +33,10 @@ #define OPT_HELP 1 -static char *config_file = NULL; -static bool verbose = false; -static char *pid_file = NULL; -static bool daemonize = false; +static char *config_file = NULL; +static bool verbose = false; +static char *pid_file = NULL; +static bool daemonize = false; t_configuration_options config_file_options = T_CONFIGURATION_OPTIONS_INITIALIZER; @@ -46,15 +46,15 @@ PGconn *local_conn = NULL; /* Collate command line errors here for friendlier reporting */ -static ItemList cli_errors = { NULL, NULL }; +static ItemList cli_errors = {NULL, NULL}; -bool startup_event_logged = false; +bool startup_event_logged = false; MonitoringState monitoring_state = MS_NORMAL; instr_time degraded_monitoring_start; static void close_connections(void); -void (*_close_connections)(void) = NULL; +void (*_close_connections) (void) = NULL; /* * Record receipt of SIGHUP; will cause configuration file to be reread @@ -76,9 +76,9 @@ static void handle_sighup(SIGNAL_ARGS); static void handle_sigint(SIGNAL_ARGS); #endif -int calculate_elapsed(instr_time start_time); -void update_registration(PGconn *conn); -void terminate(int retval); +int calculate_elapsed(instr_time start_time); +void update_registration(PGconn *conn); +void terminate(int retval); int main(int argc, char **argv) @@ -116,7 +116,7 @@ main(int argc, char **argv) set_progname(argv[0]); - srand ( time(NULL) ); + srand(time(NULL)); /* Disallow running as root */ if (geteuid() == 0) @@ -126,7 +126,7 @@ main(int argc, char **argv) "Please log in (using, e.g., \"su\") as the " "(unprivileged) user that owns " "the data directory.\n" - ), + ), progname()); exit(1); } @@ -136,7 +136,7 @@ main(int argc, char **argv) switch (c) { - /* general options */ + /* general options */ case '?': /* Actual help option given */ @@ -154,20 +154,22 @@ main(int argc, char **argv) exit(SUCCESS); case 'V': + /* - * in contrast to repmgr3 and earlier, we only display the repmgr version - * as it's not specific to a particular PostgreSQL version + * in contrast to repmgr3 and earlier, we only display the + * repmgr version as it's not specific to a particular + * PostgreSQL version */ printf("%s %s\n", progname(), REPMGR_VERSION); exit(SUCCESS); - /* configuration options */ + /* configuration options */ case 'f': config_file = optarg; break; - /* daemon options */ + /* daemon options */ case 'd': daemonize = true; @@ -177,40 +179,42 @@ main(int argc, char **argv) pid_file = optarg; break; - /* logging options */ + /* logging options */ - /* -L/--log-level */ + /* -L/--log-level */ case 'L': - { - int detected_cli_log_level = detect_log_level(optarg); - if (detected_cli_log_level != -1) { - strncpy(cli_log_level, optarg, MAXLEN); + int detected_cli_log_level = detect_log_level(optarg); + + if (detected_cli_log_level != -1) + { + strncpy(cli_log_level, optarg, MAXLEN); + } + else + { + PQExpBufferData invalid_log_level; + + initPQExpBuffer(&invalid_log_level); + appendPQExpBuffer(&invalid_log_level, + _("invalid log level \"%s\" provided"), + optarg); + item_list_append(&cli_errors, invalid_log_level.data); + termPQExpBuffer(&invalid_log_level); + } + break; } - else - { - PQExpBufferData invalid_log_level; - initPQExpBuffer(&invalid_log_level); - appendPQExpBuffer(&invalid_log_level, - _("invalid log level \"%s\" provided"), - optarg); - item_list_append(&cli_errors, invalid_log_level.data); - termPQExpBuffer(&invalid_log_level); - } - break; - } case 'v': verbose = true; break; - /* legacy options */ + /* legacy options */ case 'm': cli_monitoring_history = true; break; default: - unknown_option: + unknown_option: show_usage(); exit(ERR_BAD_CONFIG); } @@ -223,6 +227,7 @@ main(int argc, char **argv) } startup_event_logged = false; + /* * Tell the logger we're a daemon - this will ensure any output logged * before the logger is initialized will be formatted correctly @@ -230,15 +235,19 @@ main(int argc, char **argv) logger_output_mode = OM_DAEMON; /* - * Parse the configuration file, if provided. If no configuration file - * was provided, or one was but was incomplete, parse_config() will - * abort anyway, with an appropriate message. + * Parse the configuration file, if provided. If no configuration file was + * provided, or one was but was incomplete, parse_config() will abort + * anyway, with an appropriate message. */ load_config(config_file, verbose, false, &config_file_options, argv[0]); /* Some configuration file items can be overriden by command line options */ - /* Command-line parameter -L/--log-level overrides any setting in config file*/ + + /* + * Command-line parameter -L/--log-level overrides any setting in config + * file + */ if (*cli_log_level != '\0') { strncpy(config_file_options.log_level, cli_log_level, MAXLEN); @@ -304,8 +313,8 @@ main(int argc, char **argv) * point, but we'll skip that and assume the presence of a node record * means we're dealing with a supported installation. * - * The absence of a node record will also indicate that either the node - * or repmgr has not been properly configured. + * The absence of a node record will also indicate that either the node or + * repmgr has not been properly configured. */ /* Retrieve record for this node from the local database */ @@ -368,7 +377,7 @@ start_monitoring(void) local_node_info.node_name, local_node_info.node_id); - while(true) + while (true) { switch (local_node_info.type) { @@ -398,13 +407,15 @@ start_monitoring(void) void update_registration(PGconn *conn) { - bool success = update_node_record_conn_priority(local_conn, - &config_file_options); - // check values have actually changed + bool success = update_node_record_conn_priority(local_conn, + &config_file_options); + + /* check values have actually changed */ if (success == false) { PQExpBufferData errmsg; + initPQExpBuffer(&errmsg); appendPQExpBuffer(&errmsg, @@ -620,11 +631,11 @@ show_help(void) PGconn * try_reconnect(t_node_info *node_info) { - PGconn *conn; + PGconn *conn; - int i; + int i; - int max_attempts = config_file_options.reconnect_attempts; + int max_attempts = config_file_options.reconnect_attempts; for (i = 0; i < max_attempts; i++) { @@ -635,10 +646,9 @@ try_reconnect(t_node_info *node_info) log_notice(_("node has recovered, reconnecting")); /* - * XXX we should also handle the case where node is pingable - * but connection denied due to connection exhaustion - * - fall back to degraded monitoring? - * - make that configurable + * XXX we should also handle the case where node is pingable but + * connection denied due to connection exhaustion - fall back to + * degraded monitoring? - make that configurable */ conn = establish_db_connection(node_info->conninfo, false); if (PQstatus(conn) == CONNECTION_OK) @@ -680,14 +690,14 @@ calculate_elapsed(instr_time start_time) INSTR_TIME_SUBTRACT(current_time, start_time); - return (int)INSTR_TIME_GET_DOUBLE(current_time); + return (int) INSTR_TIME_GET_DOUBLE(current_time); } const char * print_monitoring_state(MonitoringState monitoring_state) { - switch(monitoring_state) + switch (monitoring_state) { case MS_NORMAL: return "normal"; @@ -730,5 +740,3 @@ terminate(int retval) exit(retval); } - - diff --git a/repmgrd.h b/repmgrd.h index 973000cb..f62ab83d 100644 --- a/repmgrd.h +++ b/repmgrd.h @@ -12,18 +12,18 @@ extern volatile sig_atomic_t got_SIGHUP; extern MonitoringState monitoring_state; -extern instr_time degraded_monitoring_start; +extern instr_time degraded_monitoring_start; extern t_configuration_options config_file_options; extern t_node_info local_node_info; -extern PGconn *local_conn; -extern bool startup_event_logged; +extern PGconn *local_conn; +extern bool startup_event_logged; -PGconn *try_reconnect(t_node_info *node_info); +PGconn *try_reconnect(t_node_info *node_info); -int calculate_elapsed(instr_time start_time); +int calculate_elapsed(instr_time start_time); const char *print_monitoring_state(MonitoringState monitoring_state); -void update_registration(PGconn *conn); -void terminate(int retval); -#endif /* _REPMGRD_H_ */ +void update_registration(PGconn *conn); +void terminate(int retval); +#endif /* _REPMGRD_H_ */ diff --git a/strutil.c b/strutil.c index 3a42700f..4caf13ce 100644 --- a/strutil.c +++ b/strutil.c @@ -76,7 +76,7 @@ maxpath_snprintf(char *str, const char *format,...) void -append_where_clause(PQExpBufferData *where_clause, const char *format, ...) +append_where_clause(PQExpBufferData *where_clause, const char *format,...) { va_list arglist; char stringbuf[MAXLEN]; @@ -85,7 +85,7 @@ append_where_clause(PQExpBufferData *where_clause, const char *format, ...) (void) xvsnprintf(stringbuf, MAXLEN, format, arglist); va_end(arglist); - if(where_clause->data[0] == '\0') + if (where_clause->data[0] == '\0') { appendPQExpBuffer(where_clause, " WHERE "); @@ -110,10 +110,10 @@ item_list_append(ItemList *item_list, const char *message) void -item_list_append_format(ItemList *item_list, const char *format, ...) +item_list_append_format(ItemList *item_list, const char *format,...) { ItemListCell *cell; - va_list arglist; + va_list arglist; cell = (ItemListCell *) pg_malloc0(sizeof(ItemListCell)); @@ -166,11 +166,11 @@ key_value_list_set(KeyValueList *item_list, const char *key, const char *value) } void -key_value_list_set_format(KeyValueList *item_list, const char *key, const char *value, ...) +key_value_list_set_format(KeyValueList *item_list, const char *key, const char *value,...) { KeyValueListCell *cell = NULL; - va_list arglist; - int keylen = 0; + va_list arglist; + int keylen = 0; cell = (KeyValueListCell *) pg_malloc0(sizeof(KeyValueListCell)); @@ -205,7 +205,7 @@ key_value_list_set_format(KeyValueList *item_list, const char *key, const char * void -key_value_list_set_output_mode (KeyValueList *item_list, const char *key, OutputMode mode) +key_value_list_set_output_mode(KeyValueList *item_list, const char *key, OutputMode mode) { KeyValueListCell *cell = NULL; @@ -250,11 +250,11 @@ check_status_list_set(CheckStatusList *list, const char *item, CheckStatus statu void -check_status_list_set_format(CheckStatusList *list, const char *item, CheckStatus status, const char *details, ...) +check_status_list_set_format(CheckStatusList *list, const char *item, CheckStatus status, const char *details,...) { CheckStatusListCell *cell; - va_list arglist; - int itemlen; + va_list arglist; + int itemlen; cell = (CheckStatusListCell *) pg_malloc0(sizeof(CheckStatusListCell)); @@ -352,7 +352,7 @@ escape_recovery_conf_value(const char *src) char * escape_string(PGconn *conn, const char *string) { - char *escaped_string; + char *escaped_string; int error; escaped_string = pg_malloc0(MAXLEN); @@ -372,7 +372,7 @@ escape_string(PGconn *conn, const char *string) char * string_skip_prefix(const char *prefix, char *string) { - int n; + int n; n = strlen(prefix); @@ -386,7 +386,7 @@ string_skip_prefix(const char *prefix, char *string) char * string_remove_trailing_newlines(char *string) { - int n; + int n; n = strlen(string) - 1; @@ -436,7 +436,7 @@ parse_follow_command(char *parsed_command, char *template, int node_id) end_ptr = parsed_command + MAXPGPATH - 1; *end_ptr = '\0'; - for(src_ptr = template; *src_ptr; src_ptr++) + for (src_ptr = template; *src_ptr; src_ptr++) { if (*src_ptr == '%') { diff --git a/strutil.h b/strutil.h index 32c6e1f9..bc1ce671 100644 --- a/strutil.h +++ b/strutil.h @@ -33,14 +33,16 @@ #define MAXLEN_STR STR(MAXLEN) -typedef enum { +typedef enum +{ CHECK_STATUS_OK = 0, CHECK_STATUS_WARNING, CHECK_STATUS_CRITICAL, CHECK_STATUS_UNKNOWN } CheckStatus; -typedef enum { +typedef enum +{ OM_NOT_SET = -1, OM_TEXT, OM_CSV, @@ -51,7 +53,7 @@ typedef enum { typedef struct ItemListCell { struct ItemListCell *next; - char *string; + char *string; } ItemListCell; typedef struct ItemList @@ -63,9 +65,9 @@ typedef struct ItemList typedef struct KeyValueListCell { struct KeyValueListCell *next; - char *key; - char *value; - OutputMode output_mode; + char *key; + char *value; + OutputMode output_mode; } KeyValueListCell; typedef struct KeyValueList @@ -78,9 +80,9 @@ typedef struct KeyValueList typedef struct CheckStatusListCell { struct CheckStatusListCell *next; - char *item; - CheckStatus status; - char *details; + char *item; + CheckStatus status; + char *details; } CheckStatusListCell; typedef struct CheckStatusList @@ -100,62 +102,58 @@ maxpath_snprintf(char *str, const char *format,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3))); extern void -item_list_append(ItemList *item_list, const char *message); + item_list_append(ItemList *item_list, const char *message); extern void -item_list_append_format(ItemList *item_list, const char *format, ...) +item_list_append_format(ItemList *item_list, const char *format,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3))); extern void -item_list_free(ItemList *item_list); + item_list_free(ItemList *item_list); extern void -key_value_list_set(KeyValueList *item_list, const char *key, const char *value); + key_value_list_set(KeyValueList *item_list, const char *key, const char *value); extern void -key_value_list_set_format(KeyValueList *item_list, const char *key, const char *value, ...) +key_value_list_set_format(KeyValueList *item_list, const char *key, const char *value,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 4))); extern void -key_value_list_set_output_mode(KeyValueList *item_list, const char *key, OutputMode mode); + key_value_list_set_output_mode(KeyValueList *item_list, const char *key, OutputMode mode); -extern const char * -key_value_list_get(KeyValueList *item_list, const char *key); +extern const char *key_value_list_get(KeyValueList *item_list, const char *key); extern void -key_value_list_free(KeyValueList *item_list); + key_value_list_free(KeyValueList *item_list); extern void -check_status_list_set(CheckStatusList *list, const char *item, CheckStatus status, const char *details); + check_status_list_set(CheckStatusList *list, const char *item, CheckStatus status, const char *details); extern void -check_status_list_set_format(CheckStatusList *list, const char *item, CheckStatus status, const char *details, ...) +check_status_list_set_format(CheckStatusList *list, const char *item, CheckStatus status, const char *details,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 4, 5))); extern void -check_status_list_free(CheckStatusList *list); + check_status_list_free(CheckStatusList *list); -extern const char * output_check_status(CheckStatus status); +extern const char *output_check_status(CheckStatus status); -extern char * -escape_recovery_conf_value(const char *src); +extern char *escape_recovery_conf_value(const char *src); -extern char * -escape_string(PGconn *conn, const char *string); +extern char *escape_string(PGconn *conn, const char *string); extern void -append_where_clause(PQExpBufferData *where_clause, const char *clause, ...) +append_where_clause(PQExpBufferData *where_clause, const char *clause,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3))); -extern char * -string_skip_prefix(const char *prefix, char *string); +extern char *string_skip_prefix(const char *prefix, char *string); extern char -*string_remove_trailing_newlines(char *string); + *string_remove_trailing_newlines(char *string); -extern char *trim(char *s); +extern char *trim(char *s); extern void -parse_follow_command(char *parsed_command, char *template, int node_id); + parse_follow_command(char *parsed_command, char *template, int node_id); -#endif /* _STRUTIL_H_ */ +#endif /* _STRUTIL_H_ */ diff --git a/voting.h b/voting.h index e9e90c42..8cd0505e 100644 --- a/voting.h +++ b/voting.h @@ -18,11 +18,12 @@ #ifndef _VOTING_H_ #define _VOTING_H_ -typedef enum { +typedef enum +{ VS_UNKNOWN = -1, VS_NO_VOTE, VS_VOTE_REQUEST_RECEIVED, VS_VOTE_INITIATED } NodeVotingStatus; -#endif /* _VOTING_H_ */ +#endif /* _VOTING_H_ */