Example #1
0
 def __init__(self, host, user, password, name, port=3306):
     Borg.__init__(self)
     self.db_host = host
     self.db_user = user
     self.db_pass = password
     self.db_name = name
     self.port = port
Example #2
0
    def __init__(self):
        """Class initialiser"""

        Borg.__init__(self, self.__class__.__name__)

        self.prepare_attributes()
        self.load()
Example #3
0
 def __init__(self, host, user, password, name, port=3306):
     Borg.__init__(self)
     self.db_host = host
     self.db_user = user
     self.db_pass = password
     self.db_name = name
     self.port = port
Example #4
0
    def __init__(self):
        """Class initialiser"""

        Borg.__init__(self, self.__class__.__name__)

        self.prepare_attributes()
        self.load()
Example #5
0
 def __init__(self):
     """Class initialiser"""
     Borg.__init__(self, self.__class__.__name__)
     self.prepare_attributes()
     try:
         dbus.service.Object.__init__(self, self.bus_name, BUS_PATH)
     except:
         None
 def test_update_state(self):
     a = Borg("Mark")
     c = ChildShare("Paul", color="red")
     self.assertIn("color", a.state)
     d = ChildNotShare("Andrew", age=5)
     a.name = "James"
     self.assertEqual(a.name, c.name)
     self.assertNotEqual(a.name, d.name)
Example #7
0
 def __init__(self):
     """Class initialiser"""
     Borg.__init__(self, self.__class__.__name__)
     self.prepare_attributes()
     try:
         dbus.service.Object.__init__(self, self.bus_name, BUS_PATH)
     except:
         None
Example #8
0
 def test_update_state(self):
     a = Borg('Mark')
     c = ChildShare('Paul', color='red')
     self.assertIn('color', a.state)
     d = ChildNotShare('Andrew', age=5)
     a.name = 'James'
     self.assertEqual(a.name, c.name)
     self.assertNotEqual(a.name, d.name)
Example #9
0
 def __init__(self):
     Borg.__init__(self)
     self.files = 0
     self.folders = 0
     self.found = 0
     self.size = 0
     self.minutes = 0
     self.seconds = 0
Example #10
0
    def __init__(self):
        """Class initialiser"""

        Borg.__init__(self, self.__class__.__name__)

        self.prepare_attributes()
        import optionparse
        self.command_line_options = optionparse.options
        self.load()
Example #11
0
 def __init__(self):
     Borg.__init__(self, self.__class__.__name__)
     self.sessionEnding = False
     self.sessionBus = dbus.SessionBus()
     # self.smknown = SMKNOWN.keys()
     #self.smknown = [ 'mock' ]
     self.smknown = ['xfce']
     # FIXME should we check for exact w/o trying one by one?
     self.ok = self.connect()
Example #12
0
    def __init__(self):
        """Class initialiser"""

        Borg.__init__(self, self.__class__.__name__)

        self.prepare_attributes()
        import optionparse
        self.command_line_options = optionparse.options
        self.load()
Example #13
0
    def __init__(self, nleaflets=None, HID=None, BAUD=None):
        """
        Args:
            HID (str):  USB hardware id, if present: only match exactly and fallback to EMULATOR_MODE otherwise
            BAUD (int): Serial baud rate - must match serial device baud exactly
        """
        Borg.__init__(self)
        QObject.__init__(self)
        if self.__dict__.get('initialized', False):
            return

        self._tserial = None
        self.nleaflets = nleaflets
        self.init_serial_interface(HID, BAUD)
        self.initialized = True
Example #14
0
    def __init__(self, nleaflets=None, HID=None, BAUD=115200):
        """
        Args:
            HID (str):  USB hardware id, if present: only match exactly and fallback to EMULATOR_MODE otherwise
            BAUD (int): Serial baud rate - must match serial device baud exactly
        """
        Borg.__init__(self)
        if '_fserial' in self.__dict__:
            return

        self._fserial = None
        self.EMULATOR_MODE = False
        self._USB_HID = HID
        self._BAUD = BAUD
        self._nleaflets = nleaflets
        self._init_hw()
Example #15
0
    def __init__ (self,dir_name=None,ignore_funs=None,elf_only=False):
        Borg.__init__(self)
        if not (dir_name):
           return
        try:
            self.f_text = open('%s/kernel.elf.txt' %dir_name)
            self.f_symtab = open('%s/kernel.elf.symtab' %dir_name)
        except :
            print "kernel.elf.* can't be opened at directory %s" %dir_name
            assert 0
        self.elf_only = elf_only
        if not elf_only:
            self.asm_fs = dict ([(x,functions[x]) for x in functions_by_tag['ASM']])
            asm_fs = self.asm_fs
            self.tcg = None
            #from original name to the cloned name
            self.to_clone_name = {}
            self.un_clone_name = {}
            for f in asm_fs:
               if 'clone' in f:
                  match = re.search('(.*)(_clone).*',f)
                  f_name = match.groups()[0]
                  self.to_clone_name[f_name] = f
                  self.un_clone_name[f] = f_name
                #print 'to_clone_name: %s' % self.to_clone_name
        #print 'un_clone_name: %s' % self.un_clone_name

        #self.insts = {}
        #funcs is a dict of func names to elfFunc objs
        self.funcs = {}
        #dict of sym names to sym objects
        self.syms = {}
        #dict of addresses to data
        self.literals = {}
        #addr -> line text
        self.lines = {}
        self.deadend_funcs = deadend_funcs
        self.dir_name = dir_name
        #maps addrs to fun name containing it
        self.addrs_to_f = {}
Example #16
0
    def __init__ (self,dir_name=None,ignore_funs=None,elf_only=False):
        Borg.__init__(self)
        if not (dir_name):
           return
        try:
            self.f_text = open('%s/kernel.elf.txt' %dir_name)
            self.f_symtab = open('%s/kernel.elf.symtab' %dir_name)
        except :
            print "kernel.elf.* can't be opened at directory %s" %dir_name
            assert 0
        self.elf_only = elf_only
        if not elf_only:
            self.asm_fs = dict ([(x,functions[x]) for x in functions_by_tag['ASM']]) 
            asm_fs = self.asm_fs
            self.tcg = None
            #from original name to the cloned name
            self.to_clone_name = {}
            self.un_clone_name = {}
            for f in asm_fs:
               if 'clone' in f:
                  match = re.search('(.*)(_clone).*',f)
                  f_name = match.groups()[0]
                  self.to_clone_name[f_name] = f
                  self.un_clone_name[f] = f_name
                #print 'to_clone_name: %s' % self.to_clone_name
        #print 'un_clone_name: %s' % self.un_clone_name

        #self.insts = {}
        #funcs is a dict of func names to elfFunc objs
        self.funcs = {}
        #dict of sym names to sym objects
        self.syms = {}
        #dict of addresses to data
        self.literals = {}
        #addr -> line text
        self.lines = {}
        self.deadend_funcs = deadend_funcs
        self.dir_name = dir_name
        #maps addrs to fun name containing it
        self.addrs_to_f = {}
Example #17
0
 def test_initial_borg_state_shall_be_init(self):
     b = Borg()
     self.assertEqual(b.state, 'Init')
Example #18
0
 def setUpClass(self):
     self.b1 = Borg()
     self.b2 = Borg()
     self.ib1 = YourBorg()
Example #19
0
 def __init__(self):
     Borg.__init__(self)
Example #20
0
 def test_two_borgs_have_different_identity(self):
     a = Borg('Mark')
     b = Borg('Luke')
     self.assertIsNot(a, b)
 def test_borg_and_childshare_share_common_state(self):
     a = Borg("Mark")
     c = ChildShare("Paul", color="red")
     self.assertEqual(a.state, c.state)
 def test_two_borgs_share_common_state(self):
     a = Borg("Mark")
     b = Borg("Luke")
     self.assertEqual(a.state, b.state)
Example #23
0
 def test_two_borgs_share_common_state(self):
     a = Borg('Mark')
     b = Borg('Luke')
     self.assertEqual(a.state, b.state)
Example #24
0
	def __init__(self):
		print "Class created: %s" % self.__class__.__name__
		Borg.__init__(self)
		
		self.gpg = gnupg.GPG(gnupghome=settings.PGPHOMEDIR)
Example #25
0
class BorgDaemon(Daemon):
    @staticmethod
    def json_callback(obj, cmd, self):
        msg = ''
        if obj['type'] == 'archive_progress':
            msg = "Files processed: {}".format(obj['nfiles'])
            self.logger.debug(msg)

            self.notification.update(NOTIFICATION_TITLE, msg,
                                     'process-working-symbolic')
            self.notification.show()

        elif obj['type'] == 'log_message' and obj[
                'name'] != 'borg.output.progress':
            msg = obj['message'].strip()
            self.logger.info(msg)

        if msg:
            self.log += msg + "\n"

    def run(self):
        self.config = configparser.ConfigParser(
            interpolation=configparser.ExtendedInterpolation(),
            inline_comment_prefixes=('#', ','))
        self.config.read(configfile)

        log_count = self.config['Common'].getint('log-count', logcount)
        log_size = self.config['Common'].getint('log-size', logsize)
        log_level = self.config['Common'].get('log-level', loglevel)
        log_file = os.path.expanduser(self.config['Common'].get(
            'log-file', logfile))

        log_formatter = logging.Formatter(
            "%(asctime)s [%(levelname)-5.5s]  %(message)s",
            "%Y-%m-%d %H:%M:%S")

        log_file_handler = RotatingFileHandler(log_file,
                                               maxBytes=log_size,
                                               backupCount=log_count)
        log_file_handler.setFormatter(log_formatter)

        log_console_handler = logging.StreamHandler()
        log_console_handler.setFormatter(log_formatter)

        self.logger = logging.getLogger("borg")
        self.logger.addHandler(log_file_handler)
        self.logger.addHandler(log_console_handler)

        # parse and set log level
        level = logging.getLevelName(log_level.upper())
        if isinstance(level, int):
            self.logger.setLevel(level)
        else:
            self.logger.setLevel(logging.INFO)

        Notify.init("BorgBackup")

        self.notifications = []
        self.log = {}

        # instantiate our borg wrapper
        self.borg = Borg(self.logger, self.json_callback, self)

        # setup schedule that will regularily execute backups
        self.sched = sched.scheduler()

        # extract all sections beginning with 'repo-'
        self.repos = [
            self.config[repo] for repo in self.config.sections()
            if repo.startswith('repo-')
        ]

        for repo in self.repos:
            # schedule backups now, will reschedule itself
            self.handle_repo(repo)

        while True:
            Gtk.main_iteration_do(False)
            self.sched.run(blocking=False)

            time.sleep(1)

    """Check if a something is an absolute filesystem path and available"""

    def path_available(self, path):
        import os

        if not path:
            return False

        path_exp = os.path.expanduser(path)
        if os.path.isabs(path_exp):
            # not an SSH target
            if not os.path.isdir(path_exp):
                return False

        return True

    def handle_repo(self, repo):
        # if everything goes well, next backup will be in ...
        next = repo.getint('frequency')

        class NotFoundException(Exception):
            pass

        class TemporarilyNotAvailableException(Exception):
            pass

        class OperationFailedException(Exception):
            pass

        try:
            if not self.path_available(repo['repo']):
                if repo.getboolean('wait-repo', False):
                    raise TemporarilyNotAvailableException(
                        'Repo {} not yet available'.format(repo['repo']))
                else:
                    raise NotFoundException('Repo {} not found'.format(
                        repo['repo']))

            for path in repo['paths'].split('\n'):
                if not path: continue
                if not self.path_available(path):
                    if repo.getboolean('wait-paths', False):
                        raise TemporarilyNotAvailableException(
                            'Path {} not yet available'.format(path))
                    else:
                        raise NotFoundException(
                            'Path {} not found'.format(path))

            if not self.backup(repo):
                raise OperationFailedException('Backup of {} failed'.format(
                    repo['repo']))

            if not self.prune(repo):
                raise OperationFailedException('Pruning of {} failed'.format(
                    repo['repo']))

        except TemporarilyNotAvailableException as e:
            # retry faster, we expect this to happen
            next = repo.getint('retry-frequency')
            # only log at level DEBUG to prevent spamming the log
            self.logger.debug(e)

            self.logger.warning('Repo {} will be retried shortly'.format(
                repo['repo']))

        except NotFoundException as e:
            self.logger.critical(e)

        except OperationFailedException as e:
            self.logger.error(e)

        finally:
            self.logger.debug('Next backup of {} in {} minutes'.format(
                repo['repo'], next))
            self.sched.enter(next * 60, 0, self.handle_repo, [repo])

    def prune(self, repo):
        self.logger.info("Pruning {}".format(repo['repo']))
        return self.borg.prune(repo)

    def backup(self, repo):
        self.logger.info("Create backup for {}".format(repo['repo']))

        self.notification = Notify.Notification.new(
            NOTIFICATION_TITLE, "Starting backup for {}".format(repo['repo']),
            'process-working-symbolic')
        self.notification.set_timeout(2000)
        self.notification.show()

        self.log = ''

        self.borg.create(repo)

        self.notification.close()

        notification_done = Notify.Notification.new(NOTIFICATION_TITLE, "Done",
                                                    'security-high-symbolic')
        notification_done.add_action('default', 'More info', click, self.log,
                                     None)
        notification_done.connect("closed", closed)
        notification_done.set_timeout(10 * 1000)
        notification_done.show()

        self.notifications.append(notification_done)

        return True
 def test_borg_and_childnotshare_do_not_share_common_state(self):
     a = Borg("Mark")
     d = ChildNotShare("Andrew", age=5)
     self.assertNotEqual(a.state, d.state)
Example #27
0
 def __init__(self, name=None):
     Borg.__init__(self)
     if name is not None:
         self.name = name
Example #28
0
 def test_borg_and_childshare_share_common_state(self):
     a = Borg('Mark')
     c = ChildShare('Paul', color='red')
     self.assertEqual(a.state, c.state)
Example #29
0
    def run(self):
        self.config = configparser.ConfigParser(
            interpolation=configparser.ExtendedInterpolation(),
            inline_comment_prefixes=('#', ','))
        self.config.read(configfile)

        log_count = self.config['Common'].getint('log-count', logcount)
        log_size = self.config['Common'].getint('log-size', logsize)
        log_level = self.config['Common'].get('log-level', loglevel)
        log_file = os.path.expanduser(self.config['Common'].get(
            'log-file', logfile))

        log_formatter = logging.Formatter(
            "%(asctime)s [%(levelname)-5.5s]  %(message)s",
            "%Y-%m-%d %H:%M:%S")

        log_file_handler = RotatingFileHandler(log_file,
                                               maxBytes=log_size,
                                               backupCount=log_count)
        log_file_handler.setFormatter(log_formatter)

        log_console_handler = logging.StreamHandler()
        log_console_handler.setFormatter(log_formatter)

        self.logger = logging.getLogger("borg")
        self.logger.addHandler(log_file_handler)
        self.logger.addHandler(log_console_handler)

        # parse and set log level
        level = logging.getLevelName(log_level.upper())
        if isinstance(level, int):
            self.logger.setLevel(level)
        else:
            self.logger.setLevel(logging.INFO)

        Notify.init("BorgBackup")

        self.notifications = []
        self.log = {}

        # instantiate our borg wrapper
        self.borg = Borg(self.logger, self.json_callback, self)

        # setup schedule that will regularily execute backups
        self.sched = sched.scheduler()

        # extract all sections beginning with 'repo-'
        self.repos = [
            self.config[repo] for repo in self.config.sections()
            if repo.startswith('repo-')
        ]

        for repo in self.repos:
            # schedule backups now, will reschedule itself
            self.handle_repo(repo)

        while True:
            Gtk.main_iteration_do(False)
            self.sched.run(blocking=False)

            time.sleep(1)
 def test_two_borgs_have_different_identity(self):
     a = Borg("Mark")
     b = Borg("Luke")
     self.assertIsNot(a, b)