Exemple #1
0
def apply_period_profile(profileid):
    # Hosts corresponding to selected profile
    hosts = BackuppcDatabase().get_hosts_by_period_profile(profileid)
    # Getting profile settings
    profile = BackuppcDatabase().edit_period_profile(profileid, {})
    # Define config dict
    config = {}
    config['FullPeriod'] = profile['full']
    config['IncrPeriod'] = profile['incr']
    # Blackout periods
    periods = profile['exclude_periods'].split('\n')
    #
    config['BlackoutPeriods'] = []
    #
    for period in periods:
        m = re.search('([0-9.]+)=>([0-9.]+):([^:]+)', period)
        config['BlackoutPeriods'] += [{ \
        'hourBegin':m.group(1), \
        'hourEnd': m.group(2), \
        'weekDays' : m.group(3) \
        }]
    #
    for host in hosts:
        set_host_config(host, config)
    # TODO : Error treatment
    return 0
Exemple #2
0
def get_global_status(entity_uuid):
    params = {'action': 'summary'}
    url = BackuppcDatabase().get_backupserver_by_entity(entity_uuid)
    if not url: return {'err': 0, 'data': {}}
    html = send_request(params, url)
    if not html:
        return _CONNECTION_ERROR
    if getHTMLerr(html):
        return getHTMLerr(html)
    result = {'err': 0, 'data': {}}
    try:
        tb_good = getTableByTitle(html, 'Hosts with good Backups')
        tb_none = getTableByTitle(html, 'Hosts with no Backups')
        # Contents
        if not (tb_good or tb_none):
            return result
        tb_good = getTableContent(tb_good)
        if not tb_good:
            tb_good = [[] for i in xrange(12)]
        tb_none = getTableContent(tb_none)
        if not tb_none:
            tb_none = [[] for i in xrange(12)]
        #
        result['data'] = { \
            'hosts':tb_good[0]+tb_none[0], \
            'full':tb_good[2]+tb_none[2], \
            'full_size':tb_good[4]+tb_none[4], \
            'incr':tb_good[6]+tb_none[6], \
            'last_backup':tb_good[8]+tb_none[8], \
            'state':tb_good[9]+tb_none[9], \
            'last_attempt':tb_good[10]+tb_none[10]
        }
    except:
        result['data'] = {}
    return result
Exemple #3
0
def getBackupServerByUUID(uuid):
    """
    @param uuid: Machine uuid
    @type uuid: str

    @returns: the Backup Server URL for the specified UUID
    @rtype: str
    """
    #return 'localhost/backuppc/index.cgi'
    from pulse2.managers.location import ComputerLocationManager
    try:
        entity_uuid = ComputerLocationManager().getMachinesLocations(
            [uuid])[uuid]['uuid']
        parent_entities = [
            entity_uuid
        ] + ComputerLocationManager().getLocationParentPath(entity_uuid)
    except:
        logger.error("Cannot get Entity for this UUID (%s)" % uuid)
        return ''
    url = ''
    for _uuid in parent_entities:
        url = BackuppcDatabase().get_backupserver_by_entity(_uuid)
        if url: return url
    # If we're here, Backup host not mapped
    logger.error(
        "Cannot get BackupServer for this UUID (%s), please check Entity <> BackupServer mappings."
        % uuid)
    return ''
Exemple #4
0
def set_host_backup_profile(uuid, newprofile):
    newprofile = int(newprofile)
    if BackuppcDatabase().set_host_backup_profile(uuid,
                                                  newprofile) and newprofile:
        # Get profile data
        profile = BackuppcDatabase().edit_backup_profile(newprofile, {})
        # Define config dict
        config = {}
        config['RsyncShareName'] = profile['sharenames'].split('\n')
        config['ClientCharset'] = profile['encoding']
        excludes = profile['excludes'].split('||')
        for i in xrange(len(excludes)):
            excludes[i] = excludes[i].split('\n')
        config['BackupFilesExclude'] = dict(
            zip(config['RsyncShareName'], excludes))
        # Setting new host config
        set_host_config(uuid, config)
Exemple #5
0
def apply_backup_profile(profileid):
    # Hosts corresponding to selected profile
    hosts = BackuppcDatabase().get_hosts_by_backup_profile(profileid)
    # Getting profile settings
    profile = BackuppcDatabase().edit_backup_profile(profileid, {})
    # Define config dict
    config = {}
    config['RsyncShareName'] = profile['sharenames'].split('\n')
    config['ClientCharset'] = profile['encoding']
    excludes = profile['excludes'].split('||')
    for i in xrange(len(excludes)):
        excludes[i] = excludes[i].split('\n')
    config['BackupFilesExclude'] = dict(zip(config['RsyncShareName'],
                                            excludes))
    for host in hosts:
        set_host_config(host, config)
    # TODO : Error treatment
    return 0
Exemple #6
0
def set_backup_for_host(uuid):
    server_url = getBackupServerByUUID(uuid)
    if not server_url: return
    config = get_host_config('', server_url)['general_config']
    try:
        newid = str(int(max(config['Hosts'].keys())) + 1)
        config['Hosts'][newid] = {
            'host': uuid,
            'dhcp': '0',
            'user': '******',
            'moreUsers': '0'
        }
    except:
        config['Hosts'] = [{
            'host': uuid,
            'dhcp': '0',
            'user': '******',
            'moreUsers': '0'
        }]
    set_host_config('', config, 1, server_url)
    #if res['err']: return res
    # Checking if host has been added, then add it to DB
    config = get_host_config('', server_url)['general_config']
    is_added = 0
    for i in config['Hosts']:
        if config['Hosts'][i]['host'].lower() == uuid.lower():
            is_added = 1
            break
    if not is_added:
        logger.error("Unable to set host on BackupPC server")
        return {'err': 22, 'errtext': 'Unable to set host on BackupPC server'}
    # Setting nmblookup cmds and Rsync cmds in conf
    # TODO : read NmbLookupCmd from ini file
    config = {}
    config[
        'NmbLookupCmd'] = '/usr/bin/python /usr/bin/pulse2-uuid-resolver -A $host'
    config[
        'NmbLookupFindHostCmd'] = '/usr/bin/python /usr/bin/pulse2-uuid-resolver $host'
    config['XferMethod'] = 'rsync'
    config[
        'RsyncClientCmd'] = '$sshPath -q -x -o StrictHostKeyChecking=no -l root $hostIP $rsyncPath $argList+'
    config[
        'RsyncClientRestoreCmd'] = '$sshPath -q -x -o StrictHostKeyChecking=no -l root $hostIP $rsyncPath $argList+'
    config[
        'RsyncRestoreArgs'] = "--numeric-ids --perms --owner --group -D --links --hard-links --times --block-size=2048 --relative --ignore-times --recursive --super".split(
            ' ')
    config['PingCmd'] = '/bin/true'
    set_host_config(uuid, config)
    # Adding host to the DB
    try:
        BackuppcDatabase().add_host(uuid)
    except:
        logger.error("Unable to add host to database")
        return {'err': 23, 'errtext': 'Unable to add host to database'}
Exemple #7
0
def set_host_period_profile(uuid, newprofile):
    newprofile = int(newprofile)
    if BackuppcDatabase().set_host_period_profile(uuid,
                                                  newprofile) and newprofile:
        # Get profile data
        profile = BackuppcDatabase().edit_period_profile(newprofile, {})
        # Define config dict
        config = {}
        config['FullPeriod'] = profile['full']
        config['IncrPeriod'] = profile['incr']
        # Blackout periods
        periods = profile['exclude_periods'].split('\n')
        #
        config['BlackoutPeriods'] = []
        #
        for period in periods:
            m = re.search('([0-9.]+)=>([0-9.]+):([^:]+)', period)
            config['BlackoutPeriods'] += [{ \
                   'hourBegin':m.group(1), \
                   'hourEnd': m.group(2), \
                   'weekDays' : m.group(3) \
                    }]
        # Setting host config
        set_host_config(uuid, config)
Exemple #8
0
def activate():
    """
    Read the plugin configuration, initialize it, and run some tests to ensure
    it is ready to operate.
    """
    logger = logging.getLogger()
    config = BackuppcConfig("backuppc")

    # Registering BackupComputers in ComputerManager
    ComputerManager().register('backuppc', BackupComputers)

    if config.disable:
        logger.warning("Plugin backuppc: disabled by configuration.")
        return False
    if not BackuppcDatabase().activate(config):
        logger.warning("Plugin backuppc: an error occurred during the database initialization")
        return False
    return True
Exemple #9
0
def unset_backup_for_host(uuid):
    if not host_exists(uuid):
        logger.warning('Backup is not set for the machine %s' % uuid)
        return
    #
    server_url = getBackupServerByUUID(uuid)
    if not server_url: return
    # Removing entry from hosts
    config = get_host_config('', server_url)['general_config']
    try:
        for i in config['Hosts'].keys():
            if config['Hosts'][i]['host'].lower() == uuid.lower():
                del config['Hosts'][i]
                set_host_config('', config, 1, server_url)
                #if res['err']: return res
                break
        else:
            logger.warning('Host is already removed from BackupPC')
    except:
        logger.warning('No host found, passing')
    # Checking if host has been removed, then remove it from DB
    config = get_host_config('', server_url)['general_config']
    if 'Hosts' in config:
        for i in config['Hosts']:
            if config['Hosts'][i]['host'].lower() == uuid.lower():
                logger.error('Unable to remove host from BackupPC')
                return {
                    'err': 37,
                    'errtext': 'Unable to remove host from BackupPC'
                }
    # Removing host from the DB
    try:
        BackuppcDatabase().remove_host(uuid)
    except:
        logger.error("Unable to remove host from database")
        return {'err': 23, 'errtext': 'Unable to remove host from database'}
Exemple #10
0
def delete_backup_profile(id):
    return BackuppcDatabase().delete_backup_profile(id)
Exemple #11
0
def add_backup_profile(profile):
    return BackuppcDatabase().add_backup_profile(profile)
Exemple #12
0
def set_backup_for_host(uuid):
    rsync_path = get_host_rsync_path(uuid)
    server_url = getBackupServerByUUID(uuid)
    machine_info = Glpi().getLastMachineInventoryFull(uuid)
    machine = dict((key, value) for (key, value) in machine_info)
    if not server_url: return
    config = get_host_config('', server_url)['general_config']
    try:
        newid = str(int(max(config['Hosts'].keys())) + 1)
        config['Hosts'][newid] = {
            'host': uuid,
            'dhcp': '0',
            'user': '******',
            'moreUsers': '0'
        }
    except:
        config['Hosts'] = [{
            'host': uuid,
            'dhcp': '0',
            'user': '******',
            'moreUsers': '0'
        }]
    set_host_config('', config, 1, server_url)
    #if res['err']: return res
    # Checking if host has been added, then add it to DB
    config = get_host_config('', server_url)['general_config']
    is_added = 0
    for i in config['Hosts']:
        if config['Hosts'][i]['host'].lower() == uuid.lower():
            is_added = 1
            break
    if not is_added:
        logger.error("Unable to set host on BackupPC server")
        return {'err': 22, 'errtext': 'Unable to set host on BackupPC server'}
    # Setting nmblookup cmds and Rsync cmds in conf
    # TODO : read NmbLookupCmd from ini file
    config = {}
    port = randint(49152, 65535)
    config['RsyncClientPath'] = "%s" % rsync_path
    config[
        'RsyncClientCmd'] = "$sshPath -q -x -o StrictHostKeyChecking=no -l pulse -p %s $rsyncPath $argList+" % port
    if machine['os'].lower() == 'macos':
        config[
            'RsyncClientRestoreCmd'] = "$sshPath -q -x -o StrictHostKeyChecking=no -l pulse -p %s localhost sudo $rsyncPath $argList+" % port
    else:
        config[
            'RsyncClientRestoreCmd'] = "$sshPath -q -x -o StrictHostKeyChecking=no -l pulse -p %s localhost $rsyncPath $argList+" % port
    config[
        'DumpPreUserCmd'] = "/usr/sbin/pulse2-connect-machine-backuppc -m %s -p %s" % (
            uuid, port)
    config[
        'DumpPostUserCmd'] = "/usr/sbin/pulse2-disconnect-machine-backuppc -m %s -p %s" % (
            uuid, port)
    config[
        'RestorePreUserCmd'] = "/usr/sbin/pulse2-connect-machine-backuppc -m %s -p %s" % (
            uuid, port)
    config[
        'RestorePostUserCmd'] = "/usr/sbin/pulse2-disconnect-machine-backuppc -m %s -p %s" % (
            uuid, port)
    config['ClientNameAlias'] = "localhost"
    config[
        'NmbLookupCmd'] = '/usr/bin/python /usr/bin/pulse2-uuid-resolver -A $host'
    config[
        'NmbLookupFindHostCmd'] = '/usr/bin/python /usr/bin/pulse2-uuid-resolver $host'
    config['XferMethod'] = 'rsync'
    config[
        'RsyncRestoreArgs'] = "--numeric-ids --perms --owner --group -D --links --hard-links --times --block-size=2048 --relative --ignore-times --recursive --super".split(
            ' ')
    config['PingCmd'] = '/bin/true'
    print "***", config, "****"
    set_host_config(uuid, config)
    # Adding host to the DB
    try:
        BackuppcDatabase().add_host(uuid, port)
    except:
        logger.error("Unable to add host to database")
        return {'err': 23, 'errtext': 'Unable to add host to database'}
Exemple #13
0
def get_host_backup_profile(uuid):
    return BackuppcDatabase().get_host_backup_profile(uuid)
Exemple #14
0
def edit_period_profile(id,override):
    return BackuppcDatabase().edit_period_profile(id,override)
Exemple #15
0
def get_period_profiles():
    return BackuppcDatabase().get_period_profiles()
Exemple #16
0
def set_host_post_backup_script(uuid, script):
    return BackuppcDatabase().set_host_post_backup_script(uuid, script)
Exemple #17
0
def get_count_of_backuped_hosts():
    """Return the number of machines which are hosted in backuppc"""
    return BackuppcDatabase().get_count_of_backuped_hosts()
Exemple #18
0
def add_period_profile(profile):
    return BackuppcDatabase().add_period_profile(profile)
Exemple #19
0
def get_all_hosts():
    """Return all the machines which are hosted in backuppc"""
    return BackuppcDatabase().get_all_hosts()
Exemple #20
0
def add_backupserver(entityuuid,serverURL):
    return BackuppcDatabase().add_backupserver(entityuuid,serverURL)
Exemple #21
0
def get_backupservers_list():
    return BackuppcDatabase().get_backupservers_list()
Exemple #22
0
def get_host_period_profile(uuid):
    return BackuppcDatabase().get_host_period_profile(uuid)
Exemple #23
0
def get_backup_profiles():
    return BackuppcDatabase().get_backup_profiles()
Exemple #24
0
def get_host_post_restore_script(uuid):
    return BackuppcDatabase().get_host_post_restore_script(uuid)
Exemple #25
0
def host_exists(uuid):
    return BackuppcDatabase().host_exists(uuid)
Exemple #26
0
def set_host_post_restore_script(uuid, script):
    return BackuppcDatabase().set_host_post_restore_script(uuid, script)
Exemple #27
0
def calldb(func, *args, **kw):
    return getattr(BackuppcDatabase(),func).__call__(*args, **kw)
Exemple #28
0
def delete_period_profile(id):
    return BackuppcDatabase().delete_period_profile(id)
Exemple #29
0
def get_host_post_backup_script(uuid):
    return BackuppcDatabase().get_host_post_backup_script(uuid)
Exemple #30
0
def get_host_backup_reverse_port(uuid):
    return BackuppcDatabase().get_host_backup_reverse_port(uuid)