Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
class TestU:
if sys.version_info[0] >= 3:
def __str__(self):
return accented
def __bytes__(self):
return b'Wrong'
else:
def __str__(self):
return b'Wrong'
def __unicode__(self):
return accented
assert (barman.utils.force_str(Test()) == accented)
assert (barman.utils.force_str(TestU()) == accented)
assert (barman.utils.force_str(Exception(Test())) == accented)
assert (barman.utils.force_str(Exception(TestU())) == accented)
assert (barman.utils.force_str(1) == '1')
assert (barman.utils.force_str('foo') == 'foo')
assert (barman.utils.force_str(('foo', 'bar')) == "('foo', 'bar')")
def connectivity_test(config):
"""
Invoke remote get-wal --test to test the connection with Barman server
:param argparse.Namespace config: the configuration from command line
"""
# Build the peek command
ssh_command = build_ssh_command(config, 'dummy_wal_name')
# Issue the command
try:
pipe = subprocess.Popen(ssh_command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
output = pipe.communicate()
print(force_str(output[0]))
sys.exit(pipe.returncode)
except subprocess.CalledProcessError as e:
exit_with_error("Impossible to invoke remote get-wal: %s" % e)
try:
server.recover(backup_id,
args.destination_directory,
tablespaces=tablespaces,
target_tli=args.target_tli,
target_time=args.target_time,
target_xid=args.target_xid,
target_lsn=args.target_lsn,
target_name=args.target_name,
target_immediate=args.target_immediate,
exclusive=args.exclusive,
remote_command=args.remote_ssh_command,
target_action=getattr(args, 'target_action', None),
standby_mode=getattr(args, 'standby_mode', None))
except RecoveryException as exc:
output.error(force_str(exc))
output.close_and_exit()
def get_setting(self, name):
"""
Get a Postgres setting with a given name
:param name: a parameter name
"""
try:
cur = self._cursor()
cur.execute('SHOW "%s"' % name.replace('"', '""'))
return cur.fetchone()[0]
except (PostgresConnectionError, psycopg2.Error) as e:
_logger.debug("Error retrieving PostgreSQL setting '%s': %s",
name.replace('"', '""'), force_str(e).strip())
return None
remote server).
:param CheckStrategy check_strategy: the strategy for the management
of the results of the various checks
"""
check_strategy.init_check('ssh')
hint = 'Barman primary node'
cmd = None
minimal_ssh_output = None
try:
cmd = UnixRemoteCommand(self.ssh_command,
self.ssh_options,
path=self.server.path)
minimal_ssh_output = ''.join(cmd.get_last_output())
except FsOperationFailed as e:
hint = force_str(e).strip()
# Output the result
check_strategy.result(self.config.name, cmd is not None, hint=hint)
# Check if the communication channel is "clean"
if minimal_ssh_output:
check_strategy.init_check('ssh output clean')
check_strategy.result(
self.config.name,
False,
hint="the configured ssh_command must not add anything to "
"the remote command output")
def reset(self):
"""
Reset the status of the class.
"""
self.environment = dict(self.extra_env)
config_file = self.backup_manager.config.config.config_file
self.environment.update({
'BARMAN_VERSION': version.__version__,
'BARMAN_SERVER': self.backup_manager.config.name,
'BARMAN_CONFIGURATION': config_file,
'BARMAN_HOOK': self.name,
'BARMAN_RETRY': str(1 if self.retry else 0),
})
if self.error:
self.environment['BARMAN_ERROR'] = force_str(self.error)
if self.phase:
self.environment['BARMAN_PHASE'] = self.phase
script_config_name = "%s_%s" % (self.phase, self.name)
else:
script_config_name = self.name
self.script = getattr(self.backup_manager.config, script_config_name,
None)
self.exit_status = None
self.exception = None
"SELECT location, "
"({pg_walfile_name_offset}(location)).*, "
"now() AS timestamp "
"FROM pg_start_backup(%s,%s) AS location"
.format(**self.name_map),
(label, self.immediate_checkpoint))
start_row = cur.fetchone()
# Rollback to release the transaction, as the connection
# is to be retained until the end of backup
conn.rollback()
return start_row
except (PostgresConnectionError, psycopg2.Error) as e:
msg = "pg_start_backup(): %s" % force_str(e).strip()
_logger.debug(msg)
raise PostgresException(msg)
:key bool log: whether to log the message
:key bool is_error: treat this message as an error
"""
# handle keyword-only parameters
log = kwargs.pop('log', True)
is_error = kwargs.pop('is_error', False)
if len(kwargs):
raise TypeError('%s() got an unexpected keyword argument %r'
% (inspect.stack()[1][3], kwargs.popitem()[0]))
if is_error:
global error_occurred
error_occurred = True
_writer.error_occurred()
# Make sure the message is an unicode string
if message:
message = force_str(message)
# dispatch the call to the output handler
getattr(_writer, level)(message, *args)
# log the message as originating from caller's caller module
if log:
exc_info = False
if level == 'exception':
level = 'error'
exc_info = True
frm = inspect.stack()[2]
mod = inspect.getmodule(frm[0])
logger = logging.getLogger(mod.__name__)
log_level = logging.getLevelName(level.upper())
logger.log(log_level, message, *args, **{'exc_info': exc_info})
# Stop the backup using the api introduced with version 9.6
cur = conn.cursor(cursor_factory=DictCursor)
cur.execute(
'SELECT end_row.lsn AS location, '
'(SELECT CASE WHEN pg_is_in_recovery() '
'THEN min_recovery_end_timeline ELSE timeline_id END '
'FROM pg_control_checkpoint(), pg_control_recovery()'
') AS timeline, '
'end_row.labelfile AS backup_label, '
'now() AS timestamp FROM pg_stop_backup(FALSE) AS end_row')
return cur.fetchone()
except (PostgresConnectionError, psycopg2.Error) as e:
msg = ("Error issuing pg_stop_backup command: %s" %
force_str(e).strip())
_logger.debug(msg)
raise PostgresException(msg)
"""
try:
cur = self._cursor(cursor_factory=DictCursor)
# We can't use the `get_setting` method here, because it
# uses `SHOW`, returning an human readable value such as "5min",
# while we prefer a raw value such as 300.
cur.execute("SELECT setting "
"FROM pg_settings "
"WHERE name='archive_timeout'")
result = cur.fetchone()
archive_timeout = int(result[0])
return archive_timeout
except ValueError as e:
_logger.error("Error retrieving archive_timeout: %s",
force_str(e).strip())
return None