pg_indent'ing all files…

Conflicts:
	version.h
This commit is contained in:
Christian Kruse
2014-03-06 16:07:01 +01:00
committed by Jaime Casanova
parent 069f9ff2ed
commit 1c67e105ff
16 changed files with 1494 additions and 1279 deletions

View File

@@ -44,9 +44,9 @@
int int
check_dir(char *dir) check_dir(char *dir)
{ {
DIR *chkdir; DIR *chkdir;
struct dirent *file; struct dirent *file;
int result = 1; int result = 1;
errno = 0; errno = 0;
@@ -58,7 +58,7 @@ check_dir(char *dir)
while ((file = readdir(chkdir)) != NULL) while ((file = readdir(chkdir)) != NULL)
{ {
if (strcmp(".", file->d_name) == 0 || if (strcmp(".", file->d_name) == 0 ||
strcmp("..", file->d_name) == 0) strcmp("..", file->d_name) == 0)
{ {
/* skip this and parent directory */ /* skip this and parent directory */
continue; continue;
@@ -71,6 +71,7 @@ check_dir(char *dir)
} }
#ifdef WIN32 #ifdef WIN32
/* /*
* This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
* released version * released version
@@ -82,7 +83,7 @@ check_dir(char *dir)
closedir(chkdir); closedir(chkdir);
if (errno != 0) if (errno != 0)
return -1; /* some kind of I/O error? */ return -1; /* some kind of I/O error? */
return result; return result;
} }
@@ -98,7 +99,7 @@ create_directory(char *dir)
return true; return true;
log_err(_("Could not create directory \"%s\": %s\n"), log_err(_("Could not create directory \"%s\": %s\n"),
dir, strerror(errno)); dir, strerror(errno));
return false; return false;
} }
@@ -127,10 +128,10 @@ mkdir_p(char *path, mode_t omode)
{ {
struct stat sb; struct stat sb;
mode_t numask, mode_t numask,
oumask; oumask;
int first, int first,
last, last,
retval; retval;
char *p; char *p;
p = path; p = path;
@@ -149,8 +150,8 @@ mkdir_p(char *path, mode_t omode)
return 1; return 1;
} }
else if (p[1] == ':' && else if (p[1] == ':' &&
((p[0] >= 'a' && p[0] <= 'z') || ((p[0] >= 'a' && p[0] <= 'z') ||
(p[0] >= 'A' && p[0] <= 'Z'))) (p[0] >= 'A' && p[0] <= 'Z')))
{ {
/* local drive */ /* local drive */
p += 2; p += 2;
@@ -221,9 +222,9 @@ bool
is_pg_dir(char *dir) is_pg_dir(char *dir)
{ {
const size_t buf_sz = 8192; const size_t buf_sz = 8192;
char path[buf_sz]; char path[buf_sz];
struct stat sb; struct stat sb;
int r; int r;
/* test pgdata */ /* test pgdata */
xsnprintf(path, buf_sz, "%s/PG_VERSION", dir); xsnprintf(path, buf_sz, "%s/PG_VERSION", dir);
@@ -243,65 +244,65 @@ is_pg_dir(char *dir)
bool bool
create_pgdir(char *dir, bool force) create_pgdir(char *dir, bool force)
{ {
bool pg_dir = false; bool pg_dir = false;
/* Check this directory could be used as a PGDATA dir */ /* Check this directory could be used as a PGDATA dir */
switch (check_dir(dir)) switch (check_dir(dir))
{ {
case 0: case 0:
/* dir not there, must create it */ /* dir not there, must create it */
log_info(_("creating directory \"%s\"...\n"), dir); log_info(_("creating directory \"%s\"...\n"), dir);
if (!create_directory(dir)) if (!create_directory(dir))
{ {
log_err(_("couldn't create directory \"%s\"...\n"), log_err(_("couldn't create directory \"%s\"...\n"),
dir); dir);
return false; return false;
} }
break;
case 1:
/* Present but empty, fix permissions and use it */
log_info(_("checking and correcting permissions on existing directory %s ...\n"),
dir);
if (!set_directory_permissions(dir))
{
log_err(_("could not change permissions of directory \"%s\": %s\n"),
dir, strerror(errno));
return false;
}
break;
case 2:
/* Present and not empty */
log_warning(_("directory \"%s\" exists but is not empty\n"),
dir);
pg_dir = is_pg_dir(dir);
/*
* we use force to reduce the time needed to restore a node which
* turn async after a failover or anything else
*/
if (pg_dir && force)
{
/* Let it continue */
break; break;
} case 1:
else if (pg_dir && !force) /* Present but empty, fix permissions and use it */
{ log_info(_("checking and correcting permissions on existing directory %s ...\n"),
log_warning(_("\nThis looks like a PostgreSQL directory.\n" dir);
"If you are sure you want to clone here, "
"please check there is no PostgreSQL server "
"running and use the --force option\n"));
return false;
}
return false; if (!set_directory_permissions(dir))
default: {
/* Trouble accessing directory */ log_err(_("could not change permissions of directory \"%s\": %s\n"),
log_err(_("could not access directory \"%s\": %s\n"), dir, strerror(errno));
dir, strerror(errno)); return false;
return false; }
break;
case 2:
/* Present and not empty */
log_warning(_("directory \"%s\" exists but is not empty\n"),
dir);
pg_dir = is_pg_dir(dir);
/*
* we use force to reduce the time needed to restore a node which
* turn async after a failover or anything else
*/
if (pg_dir && force)
{
/* Let it continue */
break;
}
else if (pg_dir && !force)
{
log_warning(_("\nThis 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 --force option\n"));
return false;
}
return false;
default:
/* Trouble accessing directory */
log_err(_("could not access directory \"%s\": %s\n"),
dir, strerror(errno));
return false;
} }
return true; return true;
} }

View File

@@ -20,11 +20,11 @@
#ifndef _REPMGR_CHECK_DIR_H_ #ifndef _REPMGR_CHECK_DIR_H_
#define _REPMGR_CHECK_DIR_H_ #define _REPMGR_CHECK_DIR_H_
int mkdir_p(char *path, mode_t omode); int mkdir_p(char *path, mode_t omode);
int check_dir(char *dir); int check_dir(char *dir);
bool create_directory(char *dir); bool create_directory(char *dir);
bool set_directory_permissions(char *dir); bool set_directory_permissions(char *dir);
bool is_pg_dir(char *dir); bool is_pg_dir(char *dir);
bool create_pgdir(char *dir, bool force); bool create_pgdir(char *dir, bool force);
#endif #endif

View File

@@ -23,13 +23,14 @@
#include "repmgr.h" #include "repmgr.h"
void void
parse_config(const char *config_file, t_configuration_options *options) parse_config(const char *config_file, t_configuration_options * options)
{ {
char *s, buff[MAXLINELENGTH]; char *s,
char name[MAXLEN]; buff[MAXLINELENGTH];
char value[MAXLEN]; char name[MAXLEN];
char value[MAXLEN];
FILE *fp = fopen (config_file, "r"); FILE *fp = fopen(config_file, "r");
/* Initialize */ /* Initialize */
memset(options->cluster_name, 0, sizeof(options->cluster_name)); memset(options->cluster_name, 0, sizeof(options->cluster_name));
@@ -56,17 +57,18 @@ parse_config(const char *config_file, t_configuration_options *options)
options->retry_promote_interval_secs = 300; options->retry_promote_interval_secs = 300;
/* /*
* Since some commands don't require a config file at all, not * Since some commands don't require a config file at all, not having one
* having one isn't necessarily a problem. * isn't necessarily a problem.
*/ */
if (fp == NULL) if (fp == NULL)
{ {
log_err(_("Did not find the configuration file '%s', continuing\n"), config_file); log_err(_("Did not find the configuration file '%s', continuing\n"),
config_file);
return; return;
} }
/* Read next line */ /* Read next line */
while ((s = fgets (buff, sizeof buff, fp)) != NULL) while ((s = fgets(buff, sizeof buff, fp)) != NULL)
{ {
/* Skip blank lines and comments */ /* Skip blank lines and comments */
if (buff[0] == '\n' || buff[0] == '#') if (buff[0] == '\n' || buff[0] == '#')
@@ -77,22 +79,23 @@ parse_config(const char *config_file, t_configuration_options *options)
/* Copy into correct entry in parameters struct */ /* Copy into correct entry in parameters struct */
if (strcmp(name, "cluster") == 0) if (strcmp(name, "cluster") == 0)
strncpy (options->cluster_name, value, MAXLEN); strncpy(options->cluster_name, value, MAXLEN);
else if (strcmp(name, "node") == 0) else if (strcmp(name, "node") == 0)
options->node = atoi(value); options->node = atoi(value);
else if (strcmp(name, "conninfo") == 0) else if (strcmp(name, "conninfo") == 0)
strncpy (options->conninfo, value, MAXLEN); strncpy(options->conninfo, value, MAXLEN);
else if (strcmp(name, "rsync_options") == 0) else if (strcmp(name, "rsync_options") == 0)
strncpy (options->rsync_options, value, QUERY_STR_LEN); strncpy(options->rsync_options, value, QUERY_STR_LEN);
else if (strcmp(name, "ssh_options") == 0) else if (strcmp(name, "ssh_options") == 0)
strncpy (options->ssh_options, value, QUERY_STR_LEN); strncpy(options->ssh_options, value, QUERY_STR_LEN);
else if (strcmp(name, "loglevel") == 0) else if (strcmp(name, "loglevel") == 0)
strncpy (options->loglevel, value, MAXLEN); strncpy(options->loglevel, value, MAXLEN);
else if (strcmp(name, "logfacility") == 0) else if (strcmp(name, "logfacility") == 0)
strncpy (options->logfacility, value, MAXLEN); strncpy(options->logfacility, value, MAXLEN);
else if (strcmp(name, "failover") == 0) else if (strcmp(name, "failover") == 0)
{ {
char failoverstr[MAXLEN]; char failoverstr[MAXLEN];
strncpy(failoverstr, value, MAXLEN); strncpy(failoverstr, value, MAXLEN);
if (strcmp(failoverstr, "manual") == 0) if (strcmp(failoverstr, "manual") == 0)
@@ -120,9 +123,9 @@ parse_config(const char *config_file, t_configuration_options *options)
else if (strcmp(name, "reconnect_interval") == 0) else if (strcmp(name, "reconnect_interval") == 0)
options->reconnect_intvl = atoi(value); options->reconnect_intvl = atoi(value);
else if (strcmp(name, "pg_bindir") == 0) else if (strcmp(name, "pg_bindir") == 0)
strncpy (options->pg_bindir, value, MAXLEN); strncpy(options->pg_bindir, value, MAXLEN);
else if (strcmp(name, "pg_ctl_options") == 0) else if (strcmp(name, "pg_ctl_options") == 0)
strncpy (options->pgctl_options, value, MAXLEN); strncpy(options->pgctl_options, value, MAXLEN);
else if (strcmp(name, "logfile") == 0) else if (strcmp(name, "logfile") == 0)
strncpy(options->logfile, value, MAXLEN); strncpy(options->logfile, value, MAXLEN);
else if (strcmp(name, "monitor_interval_secs") == 0) else if (strcmp(name, "monitor_interval_secs") == 0)
@@ -134,10 +137,10 @@ parse_config(const char *config_file, t_configuration_options *options)
} }
/* Close file */ /* Close file */
fclose (fp); fclose(fp);
/* Check config settings */ /* Check config settings */
if (strnlen(options->cluster_name, MAXLEN)==0) if (strnlen(options->cluster_name, MAXLEN) == 0)
{ {
log_err(_("Cluster name is missing. Check the configuration file.\n")); log_err(_("Cluster name is missing. Check the configuration file.\n"));
exit(ERR_BAD_CONFIG); exit(ERR_BAD_CONFIG);
@@ -176,22 +179,23 @@ parse_config(const char *config_file, t_configuration_options *options)
char * char *
trim (char *s) trim(char *s)
{ {
/* Initialize start, end pointers */ /* Initialize start, end pointers */
char *s1 = s, *s2 = &s[strlen (s) - 1]; char *s1 = s,
*s2 = &s[strlen(s) - 1];
/* Trim and delimit right side */ /* Trim and delimit right side */
while ( (isspace (*s2)) && (s2 >= s1) ) while ((isspace(*s2)) && (s2 >= s1))
--s2; --s2;
*(s2+1) = '\0'; *(s2 + 1) = '\0';
/* Trim left side */ /* Trim left side */
while ( (isspace (*s1)) && (s1 < s2) ) while ((isspace(*s1)) && (s1 < s2))
++s1; ++s1;
/* Copy finished string */ /* Copy finished string */
memmove (s, s1, s2 - s1); memmove(s, s1, s2 - s1);
s[s2 - s1 + 1] = '\0'; s[s2 - s1 + 1] = '\0';
return s; return s;
@@ -200,13 +204,13 @@ trim (char *s)
void void
parse_line(char *buff, char *name, char *value) parse_line(char *buff, char *name, char *value)
{ {
int i = 0; int i = 0;
int j = 0; int j = 0;
/* /*
* first we find the name of the parameter * first we find the name of the parameter
*/ */
for ( ; i < MAXLEN; ++i) for (; i < MAXLEN; ++i)
{ {
if (buff[i] != '=') if (buff[i] != '=')
name[j++] = buff[i]; name[j++] = buff[i];
@@ -219,7 +223,7 @@ parse_line(char *buff, char *name, char *value)
* Now the value * Now the value
*/ */
j = 0; j = 0;
for ( ++i ; i < MAXLEN; ++i) for (++i; i < MAXLEN; ++i)
if (buff[i] == '\'') if (buff[i] == '\'')
continue; continue;
else if (buff[i] != '\n') else if (buff[i] != '\n')
@@ -231,9 +235,9 @@ parse_line(char *buff, char *name, char *value)
} }
bool bool
reload_configuration(char *config_file, t_configuration_options *orig_options) reload_configuration(char *config_file, t_configuration_options * orig_options)
{ {
PGconn *conn; PGconn *conn;
t_configuration_options new_options; t_configuration_options new_options;
@@ -313,16 +317,16 @@ reload_configuration(char *config_file, t_configuration_options *orig_options)
orig_options->master_response_timeout = new_options.master_response_timeout; orig_options->master_response_timeout = new_options.master_response_timeout;
orig_options->reconnect_attempts = new_options.reconnect_attempts; orig_options->reconnect_attempts = new_options.reconnect_attempts;
orig_options->reconnect_intvl = new_options.reconnect_intvl; orig_options->reconnect_intvl = new_options.reconnect_intvl;
/* /*
* XXX These ones can change with a simple SIGHUP? * XXX These ones can change with a simple SIGHUP?
*
strcpy (orig_options->loglevel, new_options.loglevel); * strcpy (orig_options->loglevel, new_options.loglevel); strcpy
strcpy (orig_options->logfacility, new_options.logfacility); * (orig_options->logfacility, new_options.logfacility);
*
logger_shutdown(); * logger_shutdown(); XXX do we have progname here ? logger_init(progname,
XXX do we have progname here ? * orig_options.loglevel, orig_options.logfacility);
logger_init(progname, orig_options.loglevel, orig_options.logfacility); */
*/
return true; return true;
} }

View File

@@ -25,33 +25,33 @@
typedef struct typedef struct
{ {
char cluster_name[MAXLEN]; char cluster_name[MAXLEN];
int node; int node;
char conninfo[MAXLEN]; char conninfo[MAXLEN];
int failover; int failover;
int priority; int priority;
char node_name[MAXLEN]; char node_name[MAXLEN];
char promote_command[MAXLEN]; char promote_command[MAXLEN];
char follow_command[MAXLEN]; char follow_command[MAXLEN];
char loglevel[MAXLEN]; char loglevel[MAXLEN];
char logfacility[MAXLEN]; char logfacility[MAXLEN];
char rsync_options[QUERY_STR_LEN]; char rsync_options[QUERY_STR_LEN];
char ssh_options[QUERY_STR_LEN]; char ssh_options[QUERY_STR_LEN];
int master_response_timeout; int master_response_timeout;
int reconnect_attempts; int reconnect_attempts;
int reconnect_intvl; int reconnect_intvl;
char pg_bindir[MAXLEN]; char pg_bindir[MAXLEN];
char pgctl_options[MAXLEN]; char pgctl_options[MAXLEN];
char logfile[MAXLEN]; char logfile[MAXLEN];
int monitor_interval_secs; int monitor_interval_secs;
int retry_promote_interval_secs; int retry_promote_interval_secs;
} t_configuration_options; } t_configuration_options;
#define T_CONFIGURATION_OPTIONS_INITIALIZER { "", -1, "", MANUAL_FAILOVER, -1, "", "", "", "", "", "", "", -1, -1, -1, "", "", "", 0, 0 } #define T_CONFIGURATION_OPTIONS_INITIALIZER { "", -1, "", MANUAL_FAILOVER, -1, "", "", "", "", "", "", "", -1, -1, -1, "", "", "", 0, 0 }
void parse_config(const char *config_file, t_configuration_options *options); void parse_config(const char *config_file, t_configuration_options * options);
void parse_line(char *buff, char *name, char *value); void parse_line(char *buff, char *name, char *value);
char *trim(char *s); char *trim(char *s);
bool reload_configuration(char *config_file, t_configuration_options *orig_options); bool reload_configuration(char *config_file, t_configuration_options * orig_options);
#endif #endif

175
dbutils.c
View File

@@ -29,8 +29,8 @@ PGconn *
establishDBConnection(const char *conninfo, const bool exit_on_error) establishDBConnection(const char *conninfo, const bool exit_on_error)
{ {
/* Make a connection to the database */ /* Make a connection to the database */
PGconn *conn = NULL; PGconn *conn = NULL;
char connection_string[MAXLEN]; char connection_string[MAXLEN];
strcpy(connection_string, conninfo); strcpy(connection_string, conninfo);
strcat(connection_string, " fallback_application_name='repmgr'"); strcat(connection_string, " fallback_application_name='repmgr'");
@@ -40,7 +40,7 @@ establishDBConnection(const char *conninfo, const bool exit_on_error)
if ((PQstatus(conn) != CONNECTION_OK)) if ((PQstatus(conn) != CONNECTION_OK))
{ {
log_err(_("Connection to database failed: %s\n"), log_err(_("Connection to database failed: %s\n"),
PQerrorMessage(conn)); PQerrorMessage(conn));
if (exit_on_error) if (exit_on_error)
{ {
@@ -53,16 +53,17 @@ establishDBConnection(const char *conninfo, const bool exit_on_error)
} }
PGconn * PGconn *
establishDBConnectionByParams(const char *keywords[], const char *values[],const bool exit_on_error) establishDBConnectionByParams(const char *keywords[], const char *values[],
const bool exit_on_error)
{ {
/* Make a connection to the database */ /* Make a connection to the database */
PGconn *conn = PQconnectdbParams(keywords, values, true); PGconn *conn = PQconnectdbParams(keywords, values, true);
/* Check to see that the backend connection was successfully made */ /* Check to see that the backend connection was successfully made */
if ((PQstatus(conn) != CONNECTION_OK)) if ((PQstatus(conn) != CONNECTION_OK))
{ {
log_err(_("Connection to database failed: %s\n"), log_err(_("Connection to database failed: %s\n"),
PQerrorMessage(conn)); PQerrorMessage(conn));
if (exit_on_error) if (exit_on_error)
{ {
PQfinish(conn); PQfinish(conn);
@@ -84,7 +85,7 @@ is_standby(PGconn *conn)
if (res == NULL || PQresultStatus(res) != PGRES_TUPLES_OK) if (res == NULL || PQresultStatus(res) != PGRES_TUPLES_OK)
{ {
log_err(_("Can't query server mode: %s"), log_err(_("Can't query server mode: %s"),
PQerrorMessage(conn)); PQerrorMessage(conn));
result = -1; result = -1;
} }
else if (PQntuples(res) == 1 && strcmp(PQgetvalue(res, 0, 0), "t") == 0) else if (PQntuples(res) == 1 && strcmp(PQgetvalue(res, 0, 0), "t") == 0)
@@ -104,7 +105,7 @@ is_witness(PGconn *conn, char *schema, char *cluster, int node_id)
char sqlquery[QUERY_STR_LEN]; char sqlquery[QUERY_STR_LEN];
sqlquery_snprintf(sqlquery, "SELECT witness from %s.repl_nodes where cluster = '%s' and id = %d", sqlquery_snprintf(sqlquery, "SELECT witness from %s.repl_nodes where cluster = '%s' and id = %d",
schema, cluster, node_id); schema, cluster, node_id);
res = PQexec(conn, sqlquery); res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK) if (PQresultStatus(res) != PGRES_TUPLES_OK)
{ {
@@ -124,6 +125,7 @@ bool
is_pgup(PGconn *conn, int timeout) is_pgup(PGconn *conn, int timeout)
{ {
char sqlquery[QUERY_STR_LEN]; char sqlquery[QUERY_STR_LEN];
/* Check the connection status twice in case it changes after reset */ /* Check the connection status twice in case it changes after reset */
bool twice = false; bool twice = false;
@@ -134,14 +136,14 @@ is_pgup(PGconn *conn, int timeout)
{ {
if (twice) if (twice)
return false; return false;
PQreset(conn); /* reconnect */ PQreset(conn); /* reconnect */
twice = true; twice = true;
} }
else else
{ {
/* /*
* Send a SELECT 1 just to check if the connection is OK * Send a SELECT 1 just to check if the connection is OK
*/ */
if (!CancelQuery(conn, timeout)) if (!CancelQuery(conn, timeout))
goto failed; goto failed;
if (wait_connection_availability(conn, timeout) != 1) if (wait_connection_availability(conn, timeout) != 1)
@@ -151,7 +153,7 @@ is_pgup(PGconn *conn, int timeout)
if (PQsendQuery(conn, sqlquery) == 0) if (PQsendQuery(conn, sqlquery) == 0)
{ {
log_warning(_("PQsendQuery: Query could not be sent to primary. %s\n"), log_warning(_("PQsendQuery: Query could not be sent to primary. %s\n"),
PQerrorMessage(conn)); PQerrorMessage(conn));
goto failed; goto failed;
} }
if (wait_connection_availability(conn, timeout) != 1) if (wait_connection_availability(conn, timeout) != 1)
@@ -159,11 +161,15 @@ is_pgup(PGconn *conn, int timeout)
break; break;
failed: failed:
/* we need to retry, because we might just have loose the connection once */
/*
* we need to retry, because we might just have loose the
* connection once
*/
if (twice) if (twice)
return false; return false;
PQreset(conn); /* reconnect */ PQreset(conn); /* reconnect */
twice = true; twice = true;
} }
} }
@@ -176,23 +182,23 @@ failed:
* if 8 or inferior returns an empty string * if 8 or inferior returns an empty string
*/ */
char * char *
pg_version(PGconn *conn, char* major_version) pg_version(PGconn *conn, char *major_version)
{ {
PGresult *res; PGresult *res;
int major_version1; int major_version1;
char *major_version2; char *major_version2;
res = PQexec(conn, res = PQexec(conn,
"WITH pg_version(ver) AS " "WITH pg_version(ver) AS "
"(SELECT split_part(version(), ' ', 2)) " "(SELECT split_part(version(), ' ', 2)) "
"SELECT split_part(ver, '.', 1), split_part(ver, '.', 2) " "SELECT split_part(ver, '.', 1), split_part(ver, '.', 2) "
"FROM pg_version"); "FROM pg_version");
if (PQresultStatus(res) != PGRES_TUPLES_OK) if (PQresultStatus(res) != PGRES_TUPLES_OK)
{ {
log_err(_("Version check PQexec failed: %s"), log_err(_("Version check PQexec failed: %s"),
PQerrorMessage(conn)); PQerrorMessage(conn));
PQclear(res); PQclear(res);
return NULL; return NULL;
} }
@@ -204,7 +210,7 @@ pg_version(PGconn *conn, char* major_version)
{ {
/* form a major version string */ /* form a major version string */
xsnprintf(major_version, MAXVERSIONSTR, "%d.%s", major_version1, xsnprintf(major_version, MAXVERSIONSTR, "%d.%s", major_version1,
major_version2); major_version2);
} }
else else
strcpy(major_version, ""); strcpy(major_version, "");
@@ -217,21 +223,21 @@ pg_version(PGconn *conn, char* major_version)
int int
guc_set(PGconn *conn, const char *parameter, const char *op, guc_set(PGconn *conn, const char *parameter, const char *op,
const char *value) const char *value)
{ {
PGresult *res; PGresult *res;
char sqlquery[QUERY_STR_LEN]; char sqlquery[QUERY_STR_LEN];
int retval = 1; int retval = 1;
sqlquery_snprintf(sqlquery, "SELECT true FROM pg_settings " sqlquery_snprintf(sqlquery, "SELECT true FROM pg_settings "
" WHERE name = '%s' AND setting %s '%s'", " WHERE name = '%s' AND setting %s '%s'",
parameter, op, value); parameter, op, value);
res = PQexec(conn, sqlquery); res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK) if (PQresultStatus(res) != PGRES_TUPLES_OK)
{ {
log_err(_("GUC setting check PQexec failed: %s"), log_err(_("GUC setting check PQexec failed: %s"),
PQerrorMessage(conn)); PQerrorMessage(conn));
retval = -1; retval = -1;
} }
else if (PQntuples(res) == 0) else if (PQntuples(res) == 0)
@@ -249,22 +255,22 @@ guc_set(PGconn *conn, const char *parameter, const char *op,
* the pg datatype so that the comparison can be done properly. * the pg datatype so that the comparison can be done properly.
*/ */
int int
guc_set_typed(PGconn *conn, const char *parameter, const char *op, guc_set_typed(PGconn *conn, const char *parameter, const char *op,
const char *value, const char *datatype) const char *value, const char *datatype)
{ {
PGresult *res; PGresult *res;
char sqlquery[QUERY_STR_LEN]; char sqlquery[QUERY_STR_LEN];
int retval = 1; int retval = 1;
sqlquery_snprintf(sqlquery, "SELECT true FROM pg_settings " sqlquery_snprintf(sqlquery, "SELECT true FROM pg_settings "
" WHERE name = '%s' AND setting::%s %s '%s'::%s", " WHERE name = '%s' AND setting::%s %s '%s'::%s",
parameter, datatype, op, value, datatype); parameter, datatype, op, value, datatype);
res = PQexec(conn, sqlquery); res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK) if (PQresultStatus(res) != PGRES_TUPLES_OK)
{ {
log_err(_("GUC setting check PQexec failed: %s"), log_err(_("GUC setting check PQexec failed: %s"),
PQerrorMessage(conn)); PQerrorMessage(conn));
retval = -1; retval = -1;
} }
else if (PQntuples(res) == 0) else if (PQntuples(res) == 0)
@@ -281,20 +287,20 @@ guc_set_typed(PGconn *conn, const char *parameter, const char *op,
const char * const char *
get_cluster_size(PGconn *conn) get_cluster_size(PGconn *conn)
{ {
PGresult *res; PGresult *res;
const char *size = NULL; const char *size = NULL;
char sqlquery[QUERY_STR_LEN]; char sqlquery[QUERY_STR_LEN];
sqlquery_snprintf( sqlquery_snprintf(
sqlquery, sqlquery,
"SELECT pg_size_pretty(SUM(pg_database_size(oid))::bigint) " "SELECT pg_size_pretty(SUM(pg_database_size(oid))::bigint) "
" FROM pg_database "); " FROM pg_database ");
res = PQexec(conn, sqlquery); res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK) if (PQresultStatus(res) != PGRES_TUPLES_OK)
{ {
log_err(_("Get cluster size PQexec failed: %s"), log_err(_("Get cluster size PQexec failed: %s"),
PQerrorMessage(conn)); PQerrorMessage(conn));
} }
else else
{ {
@@ -309,23 +315,23 @@ get_cluster_size(PGconn *conn)
* get a connection to master by reading repl_nodes, creating a connection * get a connection to master by reading repl_nodes, creating a connection
* to each node (one at a time) and finding if it is a master or a standby * to each node (one at a time) and finding if it is a master or a standby
* *
* NB: If master_conninfo_out may be NULL. If it is non-null, it is assumed to * NB: If master_conninfo_out may be NULL. If it is non-null, it is assumed to
* point to allocated memory of MAXCONNINFO in length, and the master server * point to allocated memory of MAXCONNINFO in length, and the master server
* connection string is placed there. * connection string is placed there.
*/ */
PGconn * PGconn *
getMasterConnection(PGconn *standby_conn, char *schema, char *cluster, getMasterConnection(PGconn *standby_conn, char *schema, char *cluster,
int *master_id, char *master_conninfo_out) int *master_id, char *master_conninfo_out)
{ {
PGconn *master_conn = NULL; PGconn *master_conn = NULL;
PGresult *res1; PGresult *res1;
PGresult *res2; PGresult *res2;
char sqlquery[QUERY_STR_LEN]; char sqlquery[QUERY_STR_LEN];
char master_conninfo_stack[MAXCONNINFO]; char master_conninfo_stack[MAXCONNINFO];
char *master_conninfo = &*master_conninfo_stack; char *master_conninfo = &*master_conninfo_stack;
char schema_quoted[MAXLEN]; char schema_quoted[MAXLEN];
int i; int i;
/* /*
* If the caller wanted to get a copy of the connection info string, sub * If the caller wanted to get a copy of the connection info string, sub
@@ -340,8 +346,8 @@ getMasterConnection(PGconn *standby_conn, char *schema, char *cluster,
* Assemble the unquoted schema name * Assemble the unquoted schema name
*/ */
{ {
char *identifier = PQescapeIdentifier(standby_conn, schema, char *identifier = PQescapeIdentifier(standby_conn, schema,
strlen(schema)); strlen(schema));
maxlen_snprintf(schema_quoted, "%s", identifier); maxlen_snprintf(schema_quoted, "%s", identifier);
PQfreemem(identifier); PQfreemem(identifier);
@@ -349,17 +355,17 @@ getMasterConnection(PGconn *standby_conn, char *schema, char *cluster,
/* find all nodes belonging to this cluster */ /* find all nodes belonging to this cluster */
log_info(_("finding node list for cluster '%s'\n"), log_info(_("finding node list for cluster '%s'\n"),
cluster); cluster);
sqlquery_snprintf(sqlquery, "SELECT id, conninfo FROM %s.repl_nodes " sqlquery_snprintf(sqlquery, "SELECT id, conninfo FROM %s.repl_nodes "
" WHERE cluster = '%s' and not witness", " WHERE cluster = '%s' and not witness",
schema_quoted, cluster); schema_quoted, cluster);
res1 = PQexec(standby_conn, sqlquery); res1 = PQexec(standby_conn, sqlquery);
if (PQresultStatus(res1) != PGRES_TUPLES_OK) if (PQresultStatus(res1) != PGRES_TUPLES_OK)
{ {
log_err(_("Can't get nodes info: %s\n"), log_err(_("Can't get nodes info: %s\n"),
PQerrorMessage(standby_conn)); PQerrorMessage(standby_conn));
PQclear(res1); PQclear(res1);
return NULL; return NULL;
} }
@@ -370,7 +376,7 @@ getMasterConnection(PGconn *standby_conn, char *schema, char *cluster,
*master_id = atoi(PQgetvalue(res1, i, 0)); *master_id = atoi(PQgetvalue(res1, i, 0));
strncpy(master_conninfo, PQgetvalue(res1, i, 1), MAXCONNINFO); strncpy(master_conninfo, PQgetvalue(res1, i, 1), MAXCONNINFO);
log_info(_("checking role of cluster node '%s'\n"), log_info(_("checking role of cluster node '%s'\n"),
master_conninfo); master_conninfo);
master_conn = establishDBConnection(master_conninfo, false); master_conn = establishDBConnection(master_conninfo, false);
if (PQstatus(master_conn) != CONNECTION_OK) if (PQstatus(master_conn) != CONNECTION_OK)
@@ -378,15 +384,15 @@ getMasterConnection(PGconn *standby_conn, char *schema, char *cluster,
/* /*
* Can't use the is_standby() function here because on error that * Can't use the is_standby() function here because on error that
* function closes the connection passed and exits. This still * function closes the connection passed and exits. This still needs
* needs to close master_conn first. * to close master_conn first.
*/ */
res2 = PQexec(master_conn, "SELECT pg_is_in_recovery()"); res2 = PQexec(master_conn, "SELECT pg_is_in_recovery()");
if (PQresultStatus(res2) != PGRES_TUPLES_OK) if (PQresultStatus(res2) != PGRES_TUPLES_OK)
{ {
log_err(_("Can't get recovery state from this node: %s\n"), log_err(_("Can't get recovery state from this node: %s\n"),
PQerrorMessage(master_conn)); PQerrorMessage(master_conn));
PQclear(res2); PQclear(res2);
PQfinish(master_conn); PQfinish(master_conn);
continue; continue;
@@ -408,14 +414,13 @@ getMasterConnection(PGconn *standby_conn, char *schema, char *cluster,
} }
} }
/* If we finish this loop without finding a master then /*
* we doesn't have the info or the master has failed (or we * If we finish this loop without finding a master then we doesn't have
* reached max_connections or superuser_reserved_connections, * the info or the master has failed (or we reached max_connections or
* anything else I'm missing?). * superuser_reserved_connections, anything else I'm missing?).
* *
* Probably we will need to check the error to know if we need * Probably we will need to check the error to know if we need to start
* to start failover procedure or just fix some situation on the * failover procedure or just fix some situation on the standby.
* standby.
*/ */
PQclear(res1); PQclear(res1);
return NULL; return NULL;
@@ -423,17 +428,19 @@ getMasterConnection(PGconn *standby_conn, char *schema, char *cluster,
/* /*
* wait until current query finishes ignoring any results, this could be an async command * wait until current query finishes ignoring any results, this could be an
* or a cancelation of a query * async command or a cancelation of a query
* return 1 if Ok; 0 if any error ocurred; -1 if timeout reached * return 1 if Ok; 0 if any error ocurred; -1 if timeout reached
*/ */
int int
wait_connection_availability(PGconn *conn, long long timeout) wait_connection_availability(PGconn *conn, long long timeout)
{ {
PGresult *res; PGresult *res;
fd_set read_set; fd_set read_set;
int sock = PQsocket(conn); int sock = PQsocket(conn);
struct timeval tmout, before, after; struct timeval tmout,
before,
after;
struct timezone tz; struct timezone tz;
/* recalc to microseconds */ /* recalc to microseconds */
@@ -450,10 +457,11 @@ wait_connection_availability(PGconn *conn, long long timeout)
if (PQisBusy(conn) == 0) if (PQisBusy(conn) == 0)
{ {
do { do
{
res = PQgetResult(conn); res = PQgetResult(conn);
PQclear(res); PQclear(res);
} while(res != NULL); } while (res != NULL);
break; break;
} }
@@ -469,8 +477,8 @@ wait_connection_availability(PGconn *conn, long long timeout)
if (select(sock, &read_set, NULL, NULL, &tmout) == -1) if (select(sock, &read_set, NULL, NULL, &tmout) == -1)
{ {
log_warning( log_warning(
_("wait_connection_availability: select() returned with error: %s"), _("wait_connection_availability: select() returned with error: %s"),
strerror(errno)); strerror(errno));
return -1; return -1;
} }
gettimeofday(&after, &tz); gettimeofday(&after, &tz);
@@ -493,8 +501,8 @@ wait_connection_availability(PGconn *conn, long long timeout)
bool bool
CancelQuery(PGconn *conn, int timeout) CancelQuery(PGconn *conn, int timeout)
{ {
char errbuf[ERRBUFF_SIZE]; char errbuf[ERRBUFF_SIZE];
PGcancel *pgcancel; PGcancel *pgcancel;
if (wait_connection_availability(conn, timeout) != 1) if (wait_connection_availability(conn, timeout) != 1)
return false; return false;
@@ -505,9 +513,8 @@ CancelQuery(PGconn *conn, int timeout)
return false; return false;
/* /*
* PQcancel can only return 0 if socket()/connect()/send() * PQcancel can only return 0 if socket()/connect()/send() fails, in any
* fails, in any of those cases we can assume something * of those cases we can assume something bad happened to the connection
* bad happened to the connection
*/ */
if (PQcancel(pgcancel, errbuf, ERRBUFF_SIZE) == 0) if (PQcancel(pgcancel, errbuf, ERRBUFF_SIZE) == 0)
{ {

View File

@@ -22,23 +22,24 @@
#include "strutil.h" #include "strutil.h"
PGconn *establishDBConnection(const char *conninfo, const bool exit_on_error); PGconn *establishDBConnection(const char *conninfo, const bool exit_on_error);
PGconn *establishDBConnectionByParams(const char *keywords[], PGconn *establishDBConnectionByParams(const char *keywords[],
const char *values[], const char *values[],
const bool exit_on_error); const bool exit_on_error);
int is_standby(PGconn *conn); int is_standby(PGconn *conn);
int is_witness(PGconn *conn, char *schema, char *cluster, int node_id); int is_witness(PGconn *conn, char *schema, char *cluster, int node_id);
bool is_pgup(PGconn *conn, int timeout); bool is_pgup(PGconn *conn, int timeout);
char *pg_version(PGconn *conn, char* major_version); char *pg_version(PGconn *conn, char *major_version);
int guc_set(PGconn *conn, const char *parameter, const char *op, int guc_set(PGconn *conn, const char *parameter, const char *op,
const char *value); const char *value);
int guc_set_typed(PGconn *conn, const char *parameter, const char *op, int guc_set_typed(PGconn *conn, const char *parameter, const char *op,
const char *value, const char *datatype); const char *value, const char *datatype);
const char *get_cluster_size(PGconn *conn); const char *get_cluster_size(PGconn *conn);
PGconn *getMasterConnection(PGconn *standby_conn, char *schema, char *cluster, PGconn *getMasterConnection(PGconn *standby_conn, char *schema, char *cluster,
int *master_id, char *master_conninfo_out); int *master_id, char *master_conninfo_out);
int wait_connection_availability(PGconn *conn, long long timeout);
bool CancelQuery(PGconn *conn, int timeout);
int wait_connection_availability(PGconn *conn, long long timeout);
bool CancelQuery(PGconn *conn, int timeout);
#endif #endif

View File

@@ -34,7 +34,7 @@
#define ERR_BAD_PASSWORD 9 #define ERR_BAD_PASSWORD 9
#define ERR_STR_OVERFLOW 10 #define ERR_STR_OVERFLOW 10
#define ERR_FAILOVER_FAIL 11 #define ERR_FAILOVER_FAIL 11
#define ERR_BAD_SSH 12 #define ERR_BAD_SSH 12
#define ERR_SYS_FAILURE 13 #define ERR_SYS_FAILURE 13
#endif /* _ERRCODE_H_ */ #endif /* _ERRCODE_H_ */

111
log.c
View File

@@ -39,15 +39,18 @@
/* #define REPMGR_DEBUG */ /* #define REPMGR_DEBUG */
void stderr_log_with_level(const char *level_name, int level, const char *fmt, ...) { void
size_t len = strlen(fmt); stderr_log_with_level(const char *level_name, int level, const char *fmt,...)
char fmt1[len + 150]; {
time_t t; size_t len = strlen(fmt);
struct tm *tm; char fmt1[len + 150];
char buff[100]; time_t t;
va_list ap; struct tm *tm;
char buff[100];
va_list ap;
if(log_level >= level) { if (log_level >= level)
{
time(&t); time(&t);
tm = localtime(&t); tm = localtime(&t);
@@ -64,20 +67,20 @@ void stderr_log_with_level(const char *level_name, int level, const char *fmt, .
} }
static int detect_log_level(const char* level); static int detect_log_level(const char *level);
static int detect_log_facility(const char* facility); static int detect_log_facility(const char *facility);
int log_type = REPMGR_STDERR; int log_type = REPMGR_STDERR;
int log_level = LOG_NOTICE; int log_level = LOG_NOTICE;
bool logger_init(t_configuration_options *opts, const char* ident, const char* level, const char* facility) bool
logger_init(t_configuration_options * opts, const char *ident, const char *level, const char *facility)
{ {
int l;
int l; int f;
int f;
#ifdef HAVE_SYSLOG #ifdef HAVE_SYSLOG
int syslog_facility = DEFAULT_SYSLOG_FACILITY; int syslog_facility = DEFAULT_SYSLOG_FACILITY;
#endif #endif
#ifdef REPMGR_DEBUG #ifdef REPMGR_DEBUG
@@ -134,17 +137,17 @@ bool logger_init(t_configuration_options *opts, const char* ident, const char* l
if (log_type == REPMGR_SYSLOG) if (log_type == REPMGR_SYSLOG)
{ {
setlogmask (LOG_UPTO (log_level)); setlogmask(LOG_UPTO(log_level));
openlog (ident, LOG_CONS | LOG_PID | LOG_NDELAY, syslog_facility); openlog(ident, LOG_CONS | LOG_PID | LOG_NDELAY, syslog_facility);
stderr_log_notice(_("Setup syslog (level: %s, facility: %s)\n"), level, facility); stderr_log_notice(_("Setup syslog (level: %s, facility: %s)\n"), level, facility);
} }
#endif #endif
if (*opts->logfile) if (*opts->logfile)
{ {
FILE *fd; FILE *fd;
fd = freopen(opts->logfile, "a", stderr); fd = freopen(opts->logfile, "a", stderr);
if (fd == NULL) if (fd == NULL)
@@ -158,9 +161,9 @@ bool logger_init(t_configuration_options *opts, const char* ident, const char* l
} }
bool logger_shutdown(void) bool
logger_shutdown(void)
{ {
#ifdef HAVE_SYSLOG #ifdef HAVE_SYSLOG
if (log_type == REPMGR_SYSLOG) if (log_type == REPMGR_SYSLOG)
closelog(); closelog();
@@ -174,13 +177,15 @@ bool logger_shutdown(void)
* options, which might increase requested logging over what's specified * options, which might increase requested logging over what's specified
* in the regular configuration file. * in the regular configuration file.
*/ */
void logger_min_verbose(int minimum) void
logger_min_verbose(int minimum)
{ {
if (log_level < minimum) if (log_level < minimum)
log_level = minimum; log_level = minimum;
} }
int detect_log_level(const char* level) int
detect_log_level(const char *level)
{ {
if (!strcmp(level, "DEBUG")) if (!strcmp(level, "DEBUG"))
return LOG_DEBUG; return LOG_DEBUG;
@@ -202,40 +207,42 @@ int detect_log_level(const char* level)
return 0; return 0;
} }
int detect_log_facility(const char* facility) int
detect_log_facility(const char *facility)
{ {
int local = 0; int local = 0;
if (!strncmp(facility, "LOCAL", 5) && strlen(facility) == 6) if (!strncmp(facility, "LOCAL", 5) && strlen(facility) == 6)
{ {
local = atoi (&facility[5]); local = atoi(&facility[5]);
switch (local) switch (local)
{ {
case 0: case 0:
return LOG_LOCAL0; return LOG_LOCAL0;
break; break;
case 1: case 1:
return LOG_LOCAL1; return LOG_LOCAL1;
break; break;
case 2: case 2:
return LOG_LOCAL2; return LOG_LOCAL2;
break; break;
case 3: case 3:
return LOG_LOCAL3; return LOG_LOCAL3;
break; break;
case 4: case 4:
return LOG_LOCAL4; return LOG_LOCAL4;
break; break;
case 5: case 5:
return LOG_LOCAL5; return LOG_LOCAL5;
break; break;
case 6: case 6:
return LOG_LOCAL6; return LOG_LOCAL6;
break; break;
case 7: case 7:
return LOG_LOCAL7; return LOG_LOCAL7;
break; break;
} }
} }

35
log.h
View File

@@ -25,7 +25,9 @@
#define REPMGR_SYSLOG 1 #define REPMGR_SYSLOG 1
#define REPMGR_STDERR 2 #define REPMGR_STDERR 2
void stderr_log_with_level(const char *level_name, int level, const char *fmt, ...) __attribute__ ((format (PG_PRINTF_ATTRIBUTE, 3, 4))); void
stderr_log_with_level(const char *level_name, int level, const char *fmt,...)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 4)));
/* Standard error logging */ /* Standard error logging */
#define stderr_log_debug(...) stderr_log_with_level("DEBUG", LOG_DEBUG, __VA_ARGS__) #define stderr_log_debug(...) stderr_log_with_level("DEBUG", LOG_DEBUG, __VA_ARGS__)
@@ -88,17 +90,16 @@ void stderr_log_with_level(const char *level_name, int level, const char *fmt, .
if (log_type == REPMGR_SYSLOG) syslog(LOG_ALERT, __VA_ARGS__); \ if (log_type == REPMGR_SYSLOG) syslog(LOG_ALERT, __VA_ARGS__); \
else stderr_log_alert(__VA_ARGS__); \ else stderr_log_alert(__VA_ARGS__); \
} }
#else #else
#define LOG_EMERG 0 /* system is unusable */ #define LOG_EMERG 0 /* system is unusable */
#define LOG_ALERT 1 /* action must be taken immediately */ #define LOG_ALERT 1 /* action must be taken immediately */
#define LOG_CRIT 2 /* critical conditions */ #define LOG_CRIT 2 /* critical conditions */
#define LOG_ERR 3 /* error conditions */ #define LOG_ERR 3 /* error conditions */
#define LOG_WARNING 4 /* warning conditions */ #define LOG_WARNING 4 /* warning conditions */
#define LOG_NOTICE 5 /* normal but significant condition */ #define LOG_NOTICE 5 /* normal but significant condition */
#define LOG_INFO 6 /* informational */ #define LOG_INFO 6 /* informational */
#define LOG_DEBUG 7 /* debug-level messages */ #define LOG_DEBUG 7 /* debug-level messages */
#define log_debug(...) stderr_log_debug(__VA_ARGS__) #define log_debug(...) stderr_log_debug(__VA_ARGS__)
#define log_info(...) stderr_log_info(__VA_ARGS__) #define log_info(...) stderr_log_info(__VA_ARGS__)
@@ -108,16 +109,18 @@ void stderr_log_with_level(const char *level_name, int level, const char *fmt, .
#define log_crit(...) stderr_log_crit(__VA_ARGS__) #define log_crit(...) stderr_log_crit(__VA_ARGS__)
#define log_alert(...) stderr_log_alert(__VA_ARGS__) #define log_alert(...) stderr_log_alert(__VA_ARGS__)
#define log_emerg(...) stderr_log_emerg(__VA_ARGS__) #define log_emerg(...) stderr_log_emerg(__VA_ARGS__)
#endif #endif
/* Logger initialisation and shutdown */ /* Logger initialisation and shutdown */
bool logger_shutdown(void); bool logger_shutdown(void);
bool logger_init(t_configuration_options *opts, const char* ident, const char* level, const char* facility);
void logger_min_verbose(int minimum);
extern int log_type; bool logger_init(t_configuration_options * opts, const char *ident,
extern int log_level; const char *level, const char *facility);
void logger_min_verbose(int minimum);
extern int log_type;
extern int log_level;
#endif #endif

1236
repmgr.c

File diff suppressed because it is too large Load Diff

View File

@@ -50,24 +50,24 @@
typedef struct typedef struct
{ {
char dbname[MAXLEN]; char dbname[MAXLEN];
char host[MAXLEN]; char host[MAXLEN];
char username[MAXLEN]; char username[MAXLEN];
char dest_dir[MAXFILENAME]; char dest_dir[MAXFILENAME];
char config_file[MAXFILENAME]; char config_file[MAXFILENAME];
char remote_user[MAXLEN]; char remote_user[MAXLEN];
char wal_keep_segments[MAXLEN]; char wal_keep_segments[MAXLEN];
bool verbose; bool verbose;
bool force; bool force;
bool wait_for_master; bool wait_for_master;
bool ignore_rsync_warn; bool ignore_rsync_warn;
char masterport[MAXLEN]; char masterport[MAXLEN];
char localport[MAXLEN]; char localport[MAXLEN];
/* parameter used by CLUSTER CLEANUP */ /* parameter used by CLUSTER CLEANUP */
int keep_history; int keep_history;
} t_runtime_options; } t_runtime_options;
#define T_RUNTIME_OPTIONS_INITIALIZER { "", "", "", "", "", "", DEFAULT_WAL_KEEP_SEGMENTS, false, false, false, false, "", "", 0 } #define T_RUNTIME_OPTIONS_INITIALIZER { "", "", "", "", "", "", DEFAULT_WAL_KEEP_SEGMENTS, false, false, false, false, "", "", 0 }

767
repmgrd.c

File diff suppressed because it is too large Load Diff

View File

@@ -18,7 +18,7 @@
#include "utils/timestamp.h" #include "utils/timestamp.h"
/* same definition as the one in xlog_internal.h */ /* same definition as the one in xlog_internal.h */
#define MAXFNAMELEN 64 #define MAXFNAMELEN 64
PG_MODULE_MAGIC; PG_MODULE_MAGIC;
@@ -27,32 +27,32 @@ PG_MODULE_MAGIC;
*/ */
typedef struct repmgrSharedState typedef struct repmgrSharedState
{ {
LWLockId lock; /* protects search/modification */ LWLockId lock; /* protects search/modification */
char location[MAXFNAMELEN]; /* last known xlog location */ char location[MAXFNAMELEN]; /* last known xlog location */
TimestampTz last_updated; TimestampTz last_updated;
} repmgrSharedState; } repmgrSharedState;
/* Links to shared memory state */ /* Links to shared memory state */
static repmgrSharedState *shared_state = NULL; static repmgrSharedState *shared_state = NULL;
static shmem_startup_hook_type prev_shmem_startup_hook = NULL; static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
void _PG_init(void); void _PG_init(void);
void _PG_fini(void); void _PG_fini(void);
static void repmgr_shmem_startup(void); static void repmgr_shmem_startup(void);
static Size repmgr_memsize(void); static Size repmgr_memsize(void);
static bool repmgr_set_standby_location(char *locationstr); static bool repmgr_set_standby_location(char *locationstr);
Datum repmgr_update_standby_location(PG_FUNCTION_ARGS); Datum repmgr_update_standby_location(PG_FUNCTION_ARGS);
Datum repmgr_get_last_standby_location(PG_FUNCTION_ARGS); Datum repmgr_get_last_standby_location(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(repmgr_update_standby_location); PG_FUNCTION_INFO_V1(repmgr_update_standby_location);
PG_FUNCTION_INFO_V1(repmgr_get_last_standby_location); PG_FUNCTION_INFO_V1(repmgr_get_last_standby_location);
Datum repmgr_update_last_updated(PG_FUNCTION_ARGS); Datum repmgr_update_last_updated(PG_FUNCTION_ARGS);
Datum repmgr_get_last_updated(PG_FUNCTION_ARGS); Datum repmgr_get_last_updated(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(repmgr_update_last_updated); PG_FUNCTION_INFO_V1(repmgr_update_last_updated);
PG_FUNCTION_INFO_V1(repmgr_get_last_updated); PG_FUNCTION_INFO_V1(repmgr_get_last_updated);
@@ -68,9 +68,9 @@ _PG_init(void)
* In order to create our shared memory area, we have to be loaded via * In order to create our shared memory area, we have to be loaded via
* shared_preload_libraries. If not, fall out without hooking into any of * shared_preload_libraries. If not, fall out without hooking into any of
* the main system. (We don't throw error here because it seems useful to * the main system. (We don't throw error here because it seems useful to
* allow the repmgr functions to be created even when the * allow the repmgr functions to be created even when the module isn't
* module isn't active. The functions must protect themselves against * active. The functions must protect themselves against being called
* being called then, however.) * then, however.)
*/ */
if (!process_shared_preload_libraries_in_progress) if (!process_shared_preload_libraries_in_progress)
return; return;
@@ -120,15 +120,15 @@ repmgr_shmem_startup(void)
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE); LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
shared_state = ShmemInitStruct("repmgr shared state", shared_state = ShmemInitStruct("repmgr shared state",
sizeof(repmgrSharedState), sizeof(repmgrSharedState),
&found); &found);
if (!found) if (!found)
{ {
/* First time through ... */ /* First time through ... */
shared_state->lock = LWLockAssign(); shared_state->lock = LWLockAssign();
snprintf(shared_state->location, snprintf(shared_state->location,
sizeof(shared_state->location), "%X/%X", 0, 0); sizeof(shared_state->location), "%X/%X", 0, 0);
} }
LWLockRelease(AddinShmemInitLock); LWLockRelease(AddinShmemInitLock);
@@ -141,20 +141,20 @@ repmgr_shmem_startup(void)
static Size static Size
repmgr_memsize(void) repmgr_memsize(void)
{ {
return MAXALIGN(sizeof(repmgrSharedState)); return MAXALIGN(sizeof(repmgrSharedState));
} }
static bool static bool
repmgr_set_standby_location(char *locationstr) repmgr_set_standby_location(char *locationstr)
{ {
/* Safety check... */ /* Safety check... */
if (!shared_state) if (!shared_state)
return false; return false;
LWLockAcquire(shared_state->lock, LW_EXCLUSIVE); LWLockAcquire(shared_state->lock, LW_EXCLUSIVE);
strncpy(shared_state->location, locationstr, MAXFNAMELEN); strncpy(shared_state->location, locationstr, MAXFNAMELEN);
LWLockRelease(shared_state->lock); LWLockRelease(shared_state->lock);
return true; return true;
} }
@@ -166,7 +166,7 @@ repmgr_set_standby_location(char *locationstr)
Datum Datum
repmgr_get_last_standby_location(PG_FUNCTION_ARGS) repmgr_get_last_standby_location(PG_FUNCTION_ARGS)
{ {
char location[MAXFNAMELEN]; char location[MAXFNAMELEN];
/* Safety check... */ /* Safety check... */
if (!shared_state) if (!shared_state)
@@ -184,14 +184,14 @@ repmgr_get_last_standby_location(PG_FUNCTION_ARGS)
Datum Datum
repmgr_update_standby_location(PG_FUNCTION_ARGS) repmgr_update_standby_location(PG_FUNCTION_ARGS)
{ {
text *location = PG_GETARG_TEXT_P(0); text *location = PG_GETARG_TEXT_P(0);
char *locationstr; char *locationstr;
/* Safety check... */ /* Safety check... */
if (!shared_state) if (!shared_state)
PG_RETURN_BOOL(false); PG_RETURN_BOOL(false);
locationstr = text_to_cstring(location); locationstr = text_to_cstring(location);
PG_RETURN_BOOL(repmgr_set_standby_location(locationstr)); PG_RETURN_BOOL(repmgr_set_standby_location(locationstr));
} }
@@ -220,9 +220,9 @@ repmgr_get_last_updated(PG_FUNCTION_ARGS)
{ {
TimestampTz last_updated; TimestampTz last_updated;
/* Safety check... */ /* Safety check... */
if (!shared_state) if (!shared_state)
PG_RETURN_NULL(); PG_RETURN_NULL();
LWLockAcquire(shared_state->lock, LW_EXCLUSIVE); LWLockAcquire(shared_state->lock, LW_EXCLUSIVE);
last_updated = shared_state->last_updated; last_updated = shared_state->last_updated;

View File

@@ -25,7 +25,9 @@
#include "log.h" #include "log.h"
#include "strutil.h" #include "strutil.h"
static int xvsnprintf(char *str, size_t size, const char *format, va_list ap) __attribute__ ((format (PG_PRINTF_ATTRIBUTE, 3, 0))); static int
xvsnprintf(char *str, size_t size, const char *format, va_list ap)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 0)));
/* Add strnlen on platforms that don't have it, like OS X */ /* Add strnlen on platforms that don't have it, like OS X */
#ifndef strnlen #ifndef strnlen
@@ -33,21 +35,22 @@ size_t
strnlen(const char *s, size_t n) strnlen(const char *s, size_t n)
{ {
const char *end = (const char *) memchr(s, '\0', n); const char *end = (const char *) memchr(s, '\0', n);
return(end ? end - s : n);
return (end ? end - s : n);
} }
#endif #endif
static int static int
xvsnprintf(char *str, size_t size, const char *format, va_list ap) xvsnprintf(char *str, size_t size, const char *format, va_list ap)
{ {
int retval; int retval;
retval = vsnprintf(str, size, format, ap); retval = vsnprintf(str, size, format, ap);
if (retval >= (int)size) if (retval >= (int) size)
{ {
log_err(_("Buffer of size not large enough to format entire string '%s'\n"), log_err(_("Buffer of size not large enough to format entire string '%s'\n"),
str); str);
exit(ERR_STR_OVERFLOW); exit(ERR_STR_OVERFLOW);
} }
@@ -56,10 +59,10 @@ xvsnprintf(char *str, size_t size, const char *format, va_list ap)
int int
xsnprintf(char *str, size_t size, const char *format, ...) xsnprintf(char *str, size_t size, const char *format,...)
{ {
va_list arglist; va_list arglist;
int retval; int retval;
va_start(arglist, format); va_start(arglist, format);
retval = xvsnprintf(str, size, format, arglist); retval = xvsnprintf(str, size, format, arglist);
@@ -70,7 +73,7 @@ xsnprintf(char *str, size_t size, const char *format, ...)
int int
sqlquery_snprintf(char *str, const char *format, ...) sqlquery_snprintf(char *str, const char *format,...)
{ {
va_list arglist; va_list arglist;
int retval; int retval;
@@ -83,7 +86,8 @@ sqlquery_snprintf(char *str, const char *format, ...)
} }
int maxlen_snprintf(char *str, const char *format, ...) int
maxlen_snprintf(char *str, const char *format,...)
{ {
va_list arglist; va_list arglist;
int retval; int retval;

View File

@@ -31,13 +31,21 @@
#define MAXCONNINFO 1024 #define MAXCONNINFO 1024
extern int xsnprintf(char *str, size_t size, const char *format, ...) __attribute__ ((format (PG_PRINTF_ATTRIBUTE, 3, 4))); extern int
extern int sqlquery_snprintf(char *str, const char *format, ...) __attribute__ ((format (PG_PRINTF_ATTRIBUTE, 2, 3))); xsnprintf(char *str, size_t size, const char *format,...)
extern int maxlen_snprintf(char *str, const char *format, ...) __attribute__ ((format (PG_PRINTF_ATTRIBUTE, 2, 3))); __attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 4)));
extern int
sqlquery_snprintf(char *str, const char *format,...)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
extern int
maxlen_snprintf(char *str, const char *format,...)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
/* Add strnlen on platforms that don't have it, like OS X */ /* Add strnlen on platforms that don't have it, like OS X */
#ifndef strnlen #ifndef strnlen
extern size_t strnlen(const char *s, size_t n); extern size_t strnlen(const char *s, size_t n);
#endif #endif
#endif /* _STRUTIL_H_ */ #endif /* _STRUTIL_H_ */

View File

@@ -2,4 +2,5 @@
#define _VERSION_H_ #define _VERSION_H_
#define REPMGR_VERSION "2.0" #define REPMGR_VERSION "2.0"
#endif #endif