Esempio n. 1
0
def get_all_attendance_from_device(ip,
                                   port=4370,
                                   timeout=30,
                                   device_id=None,
                                   clear_from_device_on_fetch=False,
                                   employee_attendance_ids=None):
    #  Sample Attendance Logs [{'punch': 255, 'user_id': '22', 'uid': 12349, 'status': 1, 'timestamp': datetime.datetime(2019, 2, 26, 20, 31, 29)},{'punch': 255, 'user_id': '7', 'uid': 7, 'status': 1, 'timestamp': datetime.datetime(2019, 2, 26, 20, 31, 36)}]
    zk = ZK(ip,
            port=port,
            timeout=timeout,
            ommit_ping=config.get('DISABLE_PING', False))
    conn = None
    attendances = []
    try:
        conn = zk.connect()
        x = conn.disable_device()
        # device is disabled when fetching data
        info_logger.info("\t".join(
            (ip, "Device Disable Attempted. Result:", str(x))))
        if employee_attendance_ids is None:
            attendances = conn.get_attendance()
        else:
            for i in conn.get_attendance():
                if (i.user_id in employee_attendance_ids):
                    attendances.append(i)
        info_logger.info("\t".join(
            (ip, "Attendances Fetched:", str(len(attendances)))))
        status.set(f'{device_id}_push_timestamp', None)
        status.set(f'{device_id}_pull_timestamp', str(datetime.datetime.now()))
        if len(attendances):
            # keeping a backup before clearing data incase the programs fails.
            # if everything goes well then this file is removed automatically at the end.
            dump_file_name = config.LOGS_DIRECTORY + '/' + device_id + "_" + ip.replace(
                '.', '_') + '_last_fetch_dump.json'
            with open(dump_file_name, 'w+') as f:
                f.write(
                    json.dumps(list(map(lambda x: x.__dict__, attendances)),
                               default=datetime.datetime.timestamp))
            if clear_from_device_on_fetch:
                x = conn.clear_attendance()
                info_logger.info("\t".join(
                    (ip, "Attendance Clear Attempted. Result:", str(x))))
        x = conn.enable_device()
        info_logger.info("\t".join(
            (ip, "Device Enable Attempted. Result:", str(x))))
    except:
        error_logger.exception(
            str(ip) + ' exception when fetching from device...')
        raise Exception('Device fetch failed.')
    finally:
        if conn:
            conn.disconnect()
    return list(map(lambda x: x.__dict__, attendances))
Esempio n. 2
0
    def authenticate(self):
        # entry point for repository authentication

        try:
            self.repository.login()
        except cfg_exceptions.InvalidSession:
            (username, password) = self.get_auth_info(
                username=local_config.get('username'))

            try:
                self.repository.login(username=username, password=password)
            except cfg_exceptions.InvalidSession, e:
                rhn_log.die(1, "Session error: %s\n" % e)
Esempio n. 3
0
    def authenticate(self, username=None, password=None):
        # entry point for repository authentication

        try:
            self.repository.login()
        except cfg_exceptions.InvalidSession:
            if not username:
                username = local_config.get('username')
            if not password:
                (username, password) = self.get_auth_info(username)

            try:
                self.repository.login(username=username, password=password)
            except cfg_exceptions.InvalidSession, e:
                rhn_log.die(1, "Session error: %s\n" % e)
Esempio n. 4
0
class BaseMain:
    modes = []
    repository_class_name = "Repository"
    plugins_dir = 'config_common'
    mode_prefix = None
    config_section = None

    def usage(self, exit_code):
        print "Usage: %s MODE [ --server-name name ] [ params ]" % sys.argv[0]
        print "Valid modes are:"
        for mode in self.modes:
            print "\t%s" % mode
        sys.exit(exit_code)

    def main(self):
        args = []

        show_help = None
        debug_level = 3
        mode = None

        dict_name_opt={'--server-name': None,'--password': None,'--username': None,}
        for index in range(1,len(sys.argv)):
            arg=sys.argv[index]
            param = filter(lambda x: x[1] == 0,dict_name_opt.iteritems())
            if param:
                if arg.startswith('-') or arg in self.modes:
                  # not perfect, but at least a little bit better
                  print "Option %s requires an argument" % dict_name_opt[param[0][0]]
                  return 1
                dict_name_opt[param[0][0]] = arg
                continue

            if arg in ('--help', '-h'):
                show_help = 1
                continue

            param = [s for s in dict_name_opt.keys() if arg.startswith(s)]
            if param:
                rarg = arg[len(param[0]):]
                if not rarg:
                    dict_name_opt[param[0]] = 0
                    if index == len(sys.argv) - 1:
                       print "Option %s requires an argument" % param[0]
                       return 1
                    continue
                if rarg[0] == '=':
                   if len(rarg) == 1:
                      print "Option %s requires an argument" % param[0]
                      return 1

                   dict_name_opt[param[0]] = rarg[1:]
                   continue
                print "Unknown option %s" % arg
                return 1

            if mode is None:
                # This should be the mode
                mode = arg
                if mode == '':
                    # Bad
                    self.usage(1)

                if mode[0] == '-':
                    # Mode can't be an option
                    self.usage(1)

                if mode not in self.modes:
                    print "Unknown mode %s" % mode
                    self.usage(1)

                continue

            args.append(arg)

        server_name = dict_name_opt['--server-name']
        password = dict_name_opt['--password']
        username = dict_name_opt['--username']

        rhn_log.set_debug_level(debug_level)

        if mode is None:
            # No args were specified
            self.usage(0)

        execname = os.path.basename(sys.argv[0])
        # Class names cannot have dot in them, so strip the extension
        execname = string.split(execname, '.', 1)[0]

        mode_module = string.replace(mode, '-', '_')
        module_name = "%s_%s" % (self.mode_prefix, mode_module)
        full_module_name = "%s.%s" % (self.plugins_dir, module_name)

        try:
            module = __import__(full_module_name)
        except ImportError, e:
            rhn_log.die(1, "Unable to load plugin for mode '%s': %s" % (mode, e))

        module = getattr(module, module_name)

        if show_help:
            # Display the per-module help
            handler = module.Handler(args, None, mode=mode, exec_name=execname)
            handler.usage()
            return 0

        cfg = config.initUp2dateConfig()
        up2date_cfg = dict(cfg.items())

        if server_name:
            local_config.init(self.config_section, defaults=up2date_cfg, server_url="https://" + server_name)
        else:
            local_config.init(self.config_section, defaults=up2date_cfg)

            try:
                server_name = local_config.get('server_url')
            except InterpolationError, e:
                if e.option == 'server_url':
                    server_name = config.getServerlURL()
                    up2date_cfg['proto'] = urlsplit(server_name[0])[0]
                    if up2date_cfg['proto'] == '':
                        up2date_cfg['proto'] = 'https'
                        up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[2], server_name)
                    else:
                        up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[1], server_name)
                    server_name = (up2date_cfg['server_list'])[0]
                    local_config.init(self.config_section, defaults=up2date_cfg, server_name=server_name)
Esempio n. 5
0
            except InterpolationError, e:
                if e.option == 'server_url':
                    server_name = config.getServerlURL()
                    up2date_cfg['proto'] = urlsplit(server_name[0])[0]
                    if up2date_cfg['proto'] == '':
                        up2date_cfg['proto'] = 'https'
                        up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[2], server_name)
                    else:
                        up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[1], server_name)
                    server_name = (up2date_cfg['server_list'])[0]
                    local_config.init(self.config_section, defaults=up2date_cfg, server_name=server_name)

        print "Using server name", server_name

        # set the debug level through the config
        rhn_log.set_debug_level(int(local_config.get('debug_level') or 0))
        rhn_log.set_logfile(local_config.get('logfile') or "/var/log/rhncfg")

        # Multi-level import - __import__("foo.bar") does not return the bar
        # module, but the foo module with bar loaded
        # XXX Error checking
        repo_class = local_config.get('repository_type')
        if repo_class is None:
            rhn_log.die(1, "repository_type not set (missing configuration file?)")

        repo_module_name = "%s.%s" % (self.plugins_dir, repo_class)
        try:
            repo_module = __import__(repo_module_name)
        except ImportError, e:
            rhn_log.die(1, "Unable to load repository module:  %s" % e)
Esempio n. 6
0
        for w, p in self.workerList.items():
            try:
                rpyc.async_(w.root.killServer)
            except:
                self.addValue(p, self.notConnected)
                self.removeValue(p, self.connected)
                self.workersToRemove.append(w)
                print("notConnected port: " + str(p))
        # Bumped outside loop since dicts cannot change len at runtime
        for w in self.workersToRemove:
            self.workerList.pop(w)
        self.workersToRemove = []  # Empty list to prevent violations

    def local_log(self, *args):
        file = open("log/master_log/" + self.name + ".txt", "a+")
        for i in args:
            file.write(i + "\n")
        file.close()


if __name__ == "__main__":
    print("STARTING CLIENT")

    config, unparsed = config_args.get()
    # Verify all arguments are parsed before continuing.
    if len(unparsed) == 0:
        mr = Client(config)
    else:
        " Unparsed arguments "
        config_args.print_usage()
Esempio n. 7
0
            except InterpolationError, e:
                if e.option == 'server_url':
                    server_name = config.getServerlURL()
                    up2date_cfg['proto'] = urlsplit(server_name[0])[0]
                    if up2date_cfg['proto'] == '':
                        up2date_cfg['proto'] = 'https'
                        up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[2], server_name)
                    else:
                        up2date_cfg['server_list'] = map(lambda x: urlsplit(x)[1], server_name)
                    server_name = (up2date_cfg['server_list'])[0]
                    local_config.init(self.config_section, defaults=up2date_cfg, server_name=server_name)

        print "Using server name", server_name

        # set the debug level through the config
        rhn_log.set_debug_level(int(local_config.get('debug_level') or 0))
        rhn_log.set_logfile(local_config.get('logfile') or "/var/log/rhncfg")

        # Multi-level import - __import__("foo.bar") does not return the bar
        # module, but the foo module with bar loaded
        # XXX Error checking
        repo_class = local_config.get('repository_type')
        if repo_class is None:
            rhn_log.die(1, "repository_type not set (missing configuration file?)")

        repo_module_name = "%s.%s" % (self.plugins_dir, repo_class)
        try:
            repo_module = __import__(repo_module_name)
        except ImportError, e:
            rhn_log.die(1, "Unable to load repository module:  %s" % e)
Esempio n. 8
0
            except InterpolationError, e:
                if e.option == "server_url":
                    server_name = config.getServerlURL()
                    up2date_cfg["proto"] = urlsplit(server_name[0])[0]
                    if up2date_cfg["proto"] == "":
                        up2date_cfg["proto"] = "https"
                        up2date_cfg["server_list"] = map(lambda x: urlsplit(x)[2], server_name)
                    else:
                        up2date_cfg["server_list"] = map(lambda x: urlsplit(x)[1], server_name)
                    server_name = (up2date_cfg["server_list"])[0]
                    local_config.init(self.config_section, defaults=up2date_cfg, server_name=server_name)

        print "Using server name", server_name

        # set the debug level through the config
        rhn_log.set_debug_level(int(local_config.get("debug_level") or 0))
        rhn_log.set_logfile(local_config.get("logfile") or "/var/log/rhncfg")

        # Multi-level import - __import__("foo.bar") does not return the bar
        # module, but the foo module with bar loaded
        # XXX Error checking
        repo_class = local_config.get("repository_type")
        if repo_class is None:
            rhn_log.die(1, "repository_type not set (missing configuration file?)")

        repo_module_name = "%s.%s" % (self.plugins_dir, repo_class)
        try:
            repo_module = __import__(repo_module_name)
        except ImportError, e:
            rhn_log.die(1, "Unable to load repository module:  %s" % e)