Ejemplo n.º 1
0
    def test_xlogdb(self, lock_file_mock, os_mock, tmpdir):
        """
        Testing the normal execution of xlog-db operations.

        :param lock_file_mock: mock for LockFile object
        :param os_mock: mock for os module
        :param tmpdir: temporary directory unique to the test invocation
        """
        # unpatch os.path
        os_mock.path = os.path
        # Setup temp dir and server
        server = Server(self.build_config(tmpdir))
        # Test the execution of the fsync on xlogdb file
        with server.xlogdb('w') as fxlogdb:
            fxlogdb.write("00000000000000000000")
        # Check for calls on fsync method. If the call have been issued
        # the "exit" method of the contextmanager have been executed
        assert os_mock.fsync.called
        # Check for enter and exit calls on mocked LockFile
        lock_file_mock.return_value.__enter__.assert_called_once_with()
        lock_file_mock.return_value.__exit__.assert_called_once_with(
            None, None, None)

        os_mock.fsync.reset_mock()
        with server.xlogdb():
            # nothing to do here.
            pass
        # Check for calls on fsync method.
        # If the file is readonly exit method of the context manager must
        # skip calls on fsync method
        assert not os_mock.fsync.called
Ejemplo n.º 2
0
 def test_bad_init(self):
     """
     Check the server is buildable with an empty configuration
     """
     server = Server(build_config_from_dicts(
         main_conf={
             'conninfo': '',
             'ssh_command': '',
         }
     ).get_server('main'))
     assert server.config.disabled
     # ARCHIVER_OFF_BACKCOMPATIBILITY - START OF CODE
     # # Check that either archiver or streaming_archiver are set
     # server = Server(build_config_from_dicts(
     #     main_conf={
     #         'archiver': 'off',
     #         'streaming_archiver': 'off'
     #     }
     # ).get_server('main'))
     # assert server.config.disabled
     # assert "No archiver enabled for server 'main'. " \
     #        "Please turn on 'archiver', 'streaming_archiver' or " \
     #        "both" in server.config.msg_list
     # ARCHIVER_OFF_BACKCOMPATIBILITY - START OF CODE
     server = Server(build_config_from_dicts(
         main_conf={
             'archiver': 'off',
             'streaming_archiver': 'on',
             'slot_name': ''
         }
     ).get_server('main'))
     assert server.config.disabled
     assert "Streaming-only archiver requires 'streaming_conninfo' and " \
            "'slot_name' options to be properly configured" \
            in server.config.msg_list
Ejemplo n.º 3
0
 def test_get_wal_full_path(self, tmpdir):
     """
     Testing Server.get_wal_full_path() method
     """
     wal_name = '0000000B00000A36000000FF'
     wal_hash = wal_name[:16]
     server = Server(self.build_config(tmpdir))
     full_path = server.get_wal_full_path(wal_name)
     assert full_path == \
         str(tmpdir.join('wals').join(wal_hash).join(wal_name))
Ejemplo n.º 4
0
 def test_check_config_missing(self):
     """
     Verify the check method can be called on an empty configuration
     """
     server = Server(build_config_from_dicts(
         main_conf={
             'conninfo': '',
             'ssh_command': '',
         }
     ).get_server('main'))
     check_strategy = CheckOutputStrategy()
     server.check(check_strategy)
     assert check_strategy.has_error
Ejemplo n.º 5
0
def get_server_list(args):
    ''' Get the server list from the configuration '''
    if args.server_name[0] == 'all':
        return dict(
            (conf.name, Server(conf)) for conf in barman.__config__.servers())
    else:
        server_dict = {}
        for server in args.server_name:
            conf = barman.__config__.get_server(server)
            if conf == None:
                server_dict[server] = None
            else:
                server_dict[server] = Server(conf)
        return server_dict
Ejemplo n.º 6
0
    def test_manage_server_command(self, monkeypatch, capsys):
        """
        Test manage_server_command method checking
        the various types of error output

        :param monkeypatch monkeypatch: pytest patcher
        """
        # Build a server with a config with path conflicts
        monkeypatch.setattr(
            barman,
            "__config__",
            build_config_from_dicts(
                main_conf=build_config_dictionary(
                    {
                        "wals_directory": "/some/barman/home/main/wals",
                        "basebackups_directory": "/some/barman/home/main/wals",
                        "archiver": "on",
                    }
                )
            ),
        )
        server = Server(barman.__config__.get_server("main"))
        # Test a not blocking WARNING message
        manage_server_command(server)
        out, err = capsys.readouterr()
        # Expect an ERROR message because of conflicting paths
        assert "ERROR: Conflicting path" in err

        # Build a server with a config without path conflicts
        monkeypatch.setattr(barman, "__config__", build_config_from_dicts())
        server = Server(barman.__config__.get_server("main"))
        # Set the server as not active
        server.config.active = False
        # Request to treat inactive as errors
        to_be_executed = manage_server_command(server, inactive_is_error=True)
        out, err = capsys.readouterr()
        # Expect a ERROR message because of a not active server
        assert "ERROR: Inactive server" in err
        assert not to_be_executed

        # Request to treat inactive as warning
        to_be_executed = manage_server_command(server, inactive_is_error=False)
        out, err = capsys.readouterr()
        # Expect no error whatsoever
        assert err == ""
        assert not to_be_executed
Ejemplo n.º 7
0
 def test_init(self):
     """
     Basic initialization test with minimal parameters
     """
     server = Server(build_config_from_dicts(
         global_conf={
             'archiver': 'on'
         }).get_server('main'))
     assert not server.config.disabled
Ejemplo n.º 8
0
def main():
    parser = argparse.ArgumentParser(description="Barman plugin for NRPE.")
    parser.add_argument("-s",
                        "--server",
                        dest="server",
                        help="server to check")
    parser.add_argument('-w',
                        '--warning',
                        type=int,
                        dest="warning",
                        metavar="W",
                        help="warning threshold.")
    parser.add_argument('-c',
                        '--critical',
                        type=int,
                        dest="critical",
                        metavar="C",
                        help="critical threshold.")
    parser.add_argument(
        '-u'
        '--user',
        dest='user',
        metavar='U',
        help="user needed to run this script. If the "
        "current user is not this one, the script will try " +
        "to rerun itself using sudo.")

    subparsers = parser.add_subparsers()

    for key, value in ACTIONS.items():
        (action, help) = value
        subparser = subparsers.add_parser(key, help=help)
        subparser.set_defaults(action=action)

    parser.error = unknown

    args = parser.parse_args()

    user = pwd.getpwuid(os.getuid())[0]

    if args.user and user != args.user:
        import subprocess

        retval = subprocess.call(["/usr/bin/sudo", "-u", args.user] + sys.argv)
        raise SystemExit(retval)

    from barman.config import Config
    from barman.server import Server

    config = Config()
    config.load_configuration_files_directory()
    server = Server(config.get_server(args.server))

    try:
        args.action(server, args)
    except KeyError:
        unknown("The action %s does not exist." % args.action)
Ejemplo n.º 9
0
 def test_check_config_missing(self, tmpdir):
     """
     Verify the check method can be called on an empty configuration
     """
     server = Server(build_config_from_dicts(
         global_conf={
             # Required by server.check_archive method
             "barman_lock_directory": tmpdir.mkdir('lock').strpath
         },
         main_conf={
             'conninfo': '',
             'ssh_command': '',
             # Required by server.check_archive method
             'wals_directory': tmpdir.mkdir('wals').strpath,
         }
     ).get_server('main'))
     check_strategy = CheckOutputStrategy()
     server.check(check_strategy)
     assert check_strategy.has_error
Ejemplo n.º 10
0
 def test_bad_init(self):
     """
     Check the server is buildable with an empty configuration
     """
     server = Server(
         build_config_from_dicts(main_conf={
             'conninfo': '',
             'ssh_command': '',
         }).get_server('main'))
     assert server.config.disabled
Ejemplo n.º 11
0
    def test_xlogdb_with_exception(self, os_mock, tmpdir):
        """
        Testing the execution of xlog-db operations with an Exception

        :param os_mock: mock for os module
        :param tmpdir: temporary directory unique to the test invocation
        """
        # unpatch os.path
        os_mock.path = os.path
        # Setup temp dir and server
        server = Server(self.build_config(tmpdir))

        # Test the execution of the fsync on xlogdb file forcing an exception
        with pytest.raises(ExceptionTest):
            with server.xlogdb('w') as fxlogdb:
                fxlogdb.write("00000000000000000000")
                raise ExceptionTest()
        # Check call on fsync method. If the call have been issued,
        # the "exit" section of the contextmanager have been executed
        assert os_mock.fsync.called
Ejemplo n.º 12
0
def build_real_server(global_conf=None, main_conf=None):
    """
    Build a real Server object built from a real configuration

    :param dict[str,str|None]|None global_conf: using this dictionary
        it is possible to override or add new values to the [barman] section
    :param dict[str,str|None]|None main_conf: using this dictionary
        it is possible to override/add new values to the [main] section
    :return barman.server.Server: a barman Server object
    """
    return Server(build_config_from_dicts(
        global_conf=global_conf, main_conf=main_conf).get_server('main'))
Ejemplo n.º 13
0
 def test_check_config_missing(self, tmpdir):
     """
     Verify the check method can be called on an empty configuration
     """
     server = Server(
         build_config_from_dicts(
             global_conf={
                 # Required by server.check_archive method
                 "barman_lock_directory": tmpdir.mkdir("lock").strpath
             },
             main_conf={
                 "conninfo": "",
                 "ssh_command": "",
                 # Required by server.check_archive method
                 "wals_directory": tmpdir.mkdir("wals").strpath,
             },
         ).get_server("main")
     )
     check_strategy = CheckOutputStrategy()
     server.check(check_strategy)
     assert check_strategy.has_error
Ejemplo n.º 14
0
def cron(args):
    """ Run maintenance tasks
    """
    filename = os.path.join(barman.__config__.barman_home, '.cron.lock')
    with lockfile(filename) as locked:
        if not locked:
            yield "ERROR: Another cron is running"
            raise SystemExit, 1
        else:
            servers = [Server(conf) for conf in barman.__config__.servers()]
            for server in servers:
                for lines in server.cron(verbose=True):
                    yield lines
Ejemplo n.º 15
0
def get_server(args):
    ''' Get the server from the configuration '''
    config = barman.__config__.get_server(args.server_name)
    if not config:
        return None
    return Server(config)
Ejemplo n.º 16
0
def get_server_list(args=None,
                    skip_inactive=False,
                    skip_disabled=False,
                    on_error_stop=True,
                    suppress_error=False):
    """
    Get the server list from the configuration

    If args the parameter is None or arg.server_name is ['all']
    returns all defined servers

    :param args: an argparse namespace containing a list server_name parameter
    :param bool skip_inactive: skip inactive servers when 'all' is required
    :param bool skip_disabled: skip disabled servers when 'all' is required
    :param bool on_error_stop: stop if an error is found
    :param bool suppress_error: suppress display of errors (e.g. diagnose)
    :rtype: dict(str,barman.server.Server|None)
    """
    server_dict = {}

    # This function must to be called with in a multiple-server context
    assert not args or isinstance(args.server_name, list)

    # Generate the list of servers (required for global errors)
    available_servers = barman.__config__.server_names()

    # Get a list of configuration errors from all the servers
    global_error_list = barman.__config__.servers_msg_list

    # Global errors have higher priority
    if global_error_list:
        # Output the list of global errors
        if not suppress_error:
            for error in global_error_list:
                output.error(error)

        # If requested, exit on first error
        if on_error_stop:
            output.close_and_exit()
            # The following return statement will never be reached
            # but it is here for clarity
            return {}

    # Handle special 'all' server cases
    # - args is None
    # - 'all' special name
    if not args or 'all' in args.server_name:
        # When 'all' is used, it must be the only specified argument
        if args and len(args.server_name) != 1:
            output.error("You cannot use 'all' with other server names")
        servers = available_servers
    else:
        servers = args.server_name

    # Loop through all the requested servers
    for server in servers:
        conf = barman.__config__.get_server(server)
        if conf is None:
            # Unknown server
            server_dict[server] = None
        else:
            server_object = Server(conf)
            # Skip inactive servers, if requested
            if skip_inactive and not server_object.config.active:
                output.info("Skipping inactive server '%s'" % conf.name)
                continue
            # Skip disabled servers, if requested
            if skip_disabled and server_object.config.disabled:
                output.info("Skipping temporarily disabled server '%s'" %
                            conf.name)
                continue
            server_dict[server] = server_object

    return server_dict