def insert_empid(client, empid, security_pin, first_name, last_name, badge): try: emp = str(empid) pushdata = "table=entity;_id=" + emp + ";enabled=1" ret = push_command_insert(client, pushdata) if ret == -1: return -1 pushdata = "table=employee;_id=" + emp + ";birth_date=;pin=" + str( emp ) + ";first_name=" + first_name + ";last_name=" + last_name + ";address=;phone=;email=;national_id=;gender=0;photo=" ret = push_command_insert(client, pushdata) if ret == -1: return -1 if badge > 0: cardno = hex(badge) cardno = cardno.upper() cardno = cardno.replace('0X', "") pushdata = "table=employee_login;id_employee=" + emp + ";id_login=3;id_multi_value=1;id_action_group=1;value=" + cardno + ";salt=;" ret = push_command_insert(client, pushdata) if ret == -1: return -1 # login combination pushdata = "table=employee_login_combination;id_employee=" + emp + ";login_combination=3;" ret = push_command_insert(client, pushdata) if ret == -1: return -1 pushdata = "table=employee_login_combination;id_employee=" + emp + ";login_combination=4;" ret = push_command_insert(client, pushdata) if ret == -1: return -1 if security_pin != '': ret = set_admin(client, emp, security_pin) if ret == -1: return -1 return 0 except ConnectionResetError as e: f.error_logging(APPNAME, str(e), 'error_log', str(inspect.stack()[0][3])) return -1
def pull_data(client): try: # pull data and process clocking times no_more_ops = False while no_more_ops == False: ops = client.pull() no_more_ops = process_pull_data(ops) if no_more_ops == -1: return -1 client.ackOperation = zk_thrift.ZKProtoSyncOperation( id=-1, action=zk_thrift.ZKProtoSyncAction.ACKNOWLEDGE, timestamp=time_ms(), data=None, compressed=None) opsToPush = [] opsToPush.append(client.ackOperation) try: client.push(opsToPush) except Exception as e: return -1 return 0 except ConnectionResetError as e: f.error_logging(APPNAME, str(e), 'error_log', str(inspect.stack()[0][3])) return -1
def set_env(): global ACCESS_TERMINAL global ATTENDANCE_TERMINAL f.error_logging(APPNAME,"error_log","2","") if os.path.isfile(gl.SCRIPT_ROOT + 'database.ini'): if sqlconns.readsql_connection_timeware_main_6() == 0: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log","") return False elif sqlconns.readsql_connection_timeware_main_6() == 1: test_comms = sqlconns.testsql(gl.SERVER, gl.SQL_LOGIN, gl.PASSWORD, gl.DATABASE) if test_comms == 0: f.error_logging(APPNAME, "Error connecting to SQL server.", "error_log","") else: if os.path.isfile(gl.GENERAL_INI): fob=open(gl.GENERAL_INI, "r") listme = fob.readlines() fob.close() else: f.error_logging(APPNAME, "Error reading general.ini file.", "error_log","") return False for index in range(len(listme)): if 'server_port' in listme[index]: gl.server_port = int(str.split(listme[index],'=')[1]) if 'face_to_personnel' in listme[index]: if 'true' in str.split(listme[index],'=')[1]: gl.face_to_personnel = True if "access_terminal" in listme[index]: ACCESS_TERMINAL = int(listme[index].split("=")[1]) if "attendance_terminal" in listme[index]: ATTENDANCE_TERMINAL = int(listme[index].split("=")[1]) return True else: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log","") return False
def version_check(): if os.path.isfile(gl.LICENSE_TXT): fob = open(gl.LICENSE_TXT, "r") listme = fob.readlines() fob.close() try: version_year = sqlconns.decrypt_with_key(listme[0]) ret = sqlconns.sql_select_single_field( "SELECT TOP 1 [data] FROM tversion WHERE [property] like 'database version'" ) if ret == -1: return False database_version = str.split(ret, '.') if int(version_year) >= int('20' + database_version[0]): return True else: f.error_logging(APPNAME, "Version is out of date....cannot start.", "error_log", "") return False except Exception as e: return False else: f.error_logging(APPNAME, "Error reading license.txt file.", "error_log", "") return False
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_RUNNING) asyncoreThread = threading.Thread(target=asyncore.loop, kwargs={'timeout': 1}) asyncoreThread.start() myStatusThread = threading.Thread(target=win32event.WaitForSingleObject, args=(self.hWaitStop, win32event.INFINITE)) myStatusThread.start() log_initialise() global SERVER_STARTED while True: if myStatusThread.isAlive(): if SERVER_STARTED==0: if set_env()==True: if version_check()==True: ssl_certs = {"certfile": gl.CERT_FILE, "keyfile": gl.KEY_FILE} # "client_ssl_options=ssl_certs" simply means "listen using SSL" server = maproxy.proxyserver.ProxyServer("localhost",gl.server_port, client_ssl_options=ssl_certs) log_initialise() SERVER_STARTED = 1 server.listen(gl.https_port) logging.getLogger('tornado.access').disabled = True try: tornado.ioloop.IOLoop.current().start() SERVER_STARTED = 1 except Exception as e: f.error_logging(APPNAME, "we have an issue", "error_log", "") tornado.ioloop.IOLoop.current().stop() else: pass else: break time.sleep(1)
def main_function(): if os.path.isfile(gl.SCRIPT_ROOT + 'database.ini'): if sqlconns.readsql_connection_timeware_main_6() == 0: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log", "") return -1 elif sqlconns.readsql_connection_timeware_main_6() == 1: test_comms = sqlconns.testsql(gl.SERVER, gl.SQL_LOGIN, gl.PASSWORD, gl.DATABASE) if test_comms == 0: f.error_logging(APPNAME, "Error connecting to SQL server.", "error_log", "") return -1 else: test_pause = inbio_started() if test_pause == -1: f.error_logging( APPNAME, "Main Loop aborted due to error (check sql connection).", "error_log", "") return -1 if test_pause == True: ret = inbio_communicate() if ret == -1: f.error_logging( APPNAME, "Main Loop aborted due to error (check sql connection).", "error_log", "") return -1 else: return else: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log", "") return -1
def sql_command_args(sql, *args): try: conn = p.connect(gl.python_sql) dbcursor = conn.cursor() dbcursor.execute(sql, *args) conn.commit() except Exception as e: f.error_logging("functions", e, "sql", sql) return -1 return 0
def no_connection_error(ip_address): list = sqlconns.sql_select_into_list( "SELECT TOP 1 value FROM d_inbio_misc WHERE property like 'LOG_COMMS_FAILURES'" ) if list == -1: return if len((list)) == 0: return if list[0][0] == "0": return f.error_logging(APPNAME, "Connect failure to " + ip_address + ".", COMM_ERROR, "") return
def sql_select(sql, *args): try: conn = p.connect(gl.python_sql) dbcursor = conn.cursor() dbcursor.execute(sql, *args) sql_list = dbcursor.fetchall() conn.close() except Exception as e: f.error_logging("functions", e, "sql", sql) return -1 return sql_list
def return_version(): if os.path.isfile(gl.LICENSE_TXT): fob=open(gl.LICENSE_TXT, "r") listme = fob.readlines() fob.close() try: version_year = sqlconns.decrypt_with_key(listme[0]) return version_year except Exception as e: return False else: f.error_logging(APPNAME, "Error reading license.txt file.", "error_log","") return False
def set_env(): global ATTENDANCE_TERMINALS global ACCESS_TERMINALS maindb = 'timeware_main_6' userdb = 'timeware_user_6' path = str.replace(gl.SCRIPT_ROOT, 'iface analyser.exe', '') f.error_logging("iface analyser", path, "error_log", "") if os.path.isfile(gl.GENERAL_INI): fob = open(gl.GENERAL_INI, "r") listme = fob.readlines() fob.close() else: showdialog('Error reading general.ini file!!!!') return False try: for index in range(len(listme)): if "'" in listme[index]: continue if "access_terminal" in listme[index]: ACCESS_TERMINALS = int(listme[index].split("=")[1]) if "attendance_terminal" in listme[index]: ATTENDANCE_TERMINALS = int(listme[index].split("=")[1]) if "dbmain" in listme[index]: maindb = str.split(listme[index], '=')[1] maindb = maindb.replace("\r", "") maindb = maindb.replace("\n", "") if "dbuser" in listme[index]: userdb = str.split(listme[index], '=')[1] userdb = userdb.replace("\r", "") userdb = userdb.replace("\n", "") except Exception as e: showdialog(e) return False if os.path.isfile(gl.DATABASE_INI): if sqlconns.readsql_connection_timeware_main_6(maindb, userdb) == 0: showdialog('Error on reading database.ini!!!! ' + path) return False elif sqlconns.readsql_connection_timeware_main_6(maindb, userdb) == 1: print(gl.DATABASE) test_comms = sqlconns.testsql(gl.SERVER, gl.SQL_LOGIN, gl.PASSWORD, gl.DATABASE) if test_comms == 0: showdialog('Error connecting to database!!!! ' + path) return False else: showdialog('Error Finding database.ini ' + path) return False return True
def push_command_insert(client, pushdata): try: client.pushdata = zk_thrift.ZKProtoSyncOperation( id=-1, action=zk_thrift.ZKProtoSyncAction.INSERT, timestamp=time_ms(), data=pushdata, compressed=None) opsToInsert = [] opsToInsert.append(client.pushdata) client.push(opsToInsert) except Exception as e: f.error_logging(APPNAME, str(e), 'error_log', str(inspect.stack()[0][3])) return -1
def sql_select_single_field(sql): #note use of fecthone try: data = "" conn = p.connect(gl.python_sql) dbcursor = conn.cursor() dbcursor.execute(sql) row = dbcursor.fetchone() if row: data = str(row[0]) conn.close() except Exception as e: f.error_logging("functions", e, "sql", sql) return -1 return data
def readsql_connection_timeware_main_6(maindb, userdb): gl.TIMEWARE_MAIN_DB = maindb gl.TIMEWARE_USER_DB = userdb fob=open(gl.SCRIPT_ROOT + "database.ini", "r") listme = fob.readlines() fob.close() for position, item in enumerate(listme): if gl.TIMEWARE_MAIN_DB.lower() in str(item).lower(): list1 = str(item).split(",") gl.SERVER = list1[0] gl.SQL_LOGIN = decrypt_with_key(list1[1]) gl.PASSWORD = decrypt_with_key(list1[2]) gl.DATABASE = gl.TIMEWARE_MAIN_DB return 1 else: f.error_logging("ifaceserver", "Cannot find database - " + maindb, "error_log", "") return 0
def build_zpad_command_list(client): try: tx = "SELECT employee_id,[index] from d_zpad_events" list_to_update = sqlconns.sql_select_into_list(tx) if list_to_update == -1: return -1 for n in range(len(list_to_update)): tx = "SELECT TOP 1 temployee.employee_id,security_pin,first_name,last_name,badge, exclude_from_calculation FROM temployee LEFT OUTER JOIN" \ " temployee_status ON temployee.employee_status_id = temployee_status.employee_status_id" \ " WHERE employee_id = " + str(list_to_update[n][0]) emp_details = sqlconns.sql_select_into_list(tx) if emp_details == -1: return -1 if len(emp_details) == 0: ret = del_empid(client, str(list_to_update[n][0])) ret = sqlconns.sql_command( "DELETE FROM d_zpad_events WHERE employee_id = ?", list_to_update[n][0]) if ret == 1: return -1 for y in range(len(emp_details)): empid = int(emp_details[y][0]) if emp_details[y][1] != None: security_pin = str(emp_details[y][1]) else: security_pin = '' first_name = str(emp_details[y][2]) last_name = str(emp_details[y][3]) if emp_details[y][4] != None: badge = int(emp_details[y][4]) else: badge = 0 exclude_from_calculation = str(emp_details[y][5]) ret = del_empid(client, empid) if exclude_from_calculation == "0": ret = insert_empid(client, empid, security_pin, first_name, last_name, badge) if ret == -1: return -1 else: ret = sqlconns.sql_command( "DELETE FROM d_zpad_events WHERE employee_id = ?", empid) if ret == 1: return -1 except ConnectionResetError as e: f.error_logging(APPNAME, str(e), 'error_log', str(inspect.stack()[0][3])) return -1
def del_empid(client, empid): try: pushdata = 'table=attendance_log;id_employee=' + str(empid) ret = push_command_delete(client, pushdata) pushdata = 'table=employee_login_combination;id_employee=' + str(empid) ret = push_command_delete(client, pushdata) pushdata = 'table=role2entity;id_entity=' + str(empid) ret = push_command_delete(client, pushdata) pushdata = "table=employee_login;id_employee=" + str(empid) ret = push_command_delete(client, pushdata) pushdata = "table=employee;_id=" + str(empid) ret = push_command_delete(client, pushdata) pushdata = "table=entity;_id=" + str(empid) ret = push_command_delete(client, pushdata) return 0 except ConnectionResetError as e: f.error_logging(APPNAME, str(e), 'error_log', str(inspect.stack()[0][3])) return -1
def sql_select_single_field_timeware_user(sql, *args): #note use of fecthone try: data = "" dial_string = gl.python_sql dial_string = str.replace(dial_string, gl.TIMEWARE_MAIN_DB,gl.TIMEWARE_USER_DB) #print(dial_string) conn = p.connect(dial_string) dbcursor = conn.cursor() dbcursor.execute(sql, *args) row = dbcursor.fetchone() if row: data = str(row[0]) conn.close() except Exception as e: #print(e) f.error_logging("functions",e,"sql",sql) return -1 return data
def set_admin(client, empid, pwd): try: hash_object = hashlib.md5(pwd.encode()) pwd = hash_object.hexdigest() pushdata = "table=employee_login;id_employee=" + str( empid ) + ";id_login=1;id_multi_value=0;id_action_group=1;value=" + pwd + ";salt=;" ret = push_command_insert(client, pushdata) if ret == -1: return -1 for n in range(4): role_id = str(n + 1) pushdata = "table=role2entity;id_role=" + role_id + ";id_entity=" + str( empid) ret = push_command_insert(client, pushdata) if ret == -1: return -1 return except Exception as e: f.error_logging(APPNAME, str(e), 'error_log', str(inspect.stack()[0][3])) return -1
def set_env(): if os.path.isfile(gl.SCRIPT_ROOT + 'database.ini'): if sqlconns.readsql_connection_timeware_main_6() == 0: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log", "") return False elif sqlconns.readsql_connection_timeware_main_6() == 1: test_comms = sqlconns.testsql(gl.SERVER, gl.SQL_LOGIN, gl.PASSWORD, gl.DATABASE) if test_comms == 0: f.error_logging(APPNAME, "Error connecting to SQL server.", "error_log", "") else: if os.path.isfile(gl.GENERAL_INI): fob = open(gl.GENERAL_INI, "r") listme = fob.readlines() fob.close() else: f.error_logging(APPNAME, "Error reading general.ini file.", "error_log", "") return False try: for index in range(len(listme)): if "'" in listme[index]: continue if 'https_port' in listme[index]: gl.https_port = int( str.split(listme[index], '=')[1]) if 'server_port' in listme[index]: gl.server_port = int( str.split(listme[index], '=')[1]) f.error_logging(APPNAME, "Port is now: " + str(gl.https_port), "error_log", "") except Exception as e: return False return True else: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log", "") return False
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_RUNNING) asyncoreThread = threading.Thread(target=asyncore.loop, kwargs={'timeout': 1}) asyncoreThread.start() myStatusThread = threading.Thread( target=win32event.WaitForSingleObject, args=(self.hWaitStop, win32event.INFINITE)) myStatusThread.start() log_initialise() county = 0 global SERVER_STARTED while True: if myStatusThread.isAlive(): county += 1 if county == 10: dte = str(datetime.datetime.now()) e = open("c:/temp/1log.txt", 'a') e.write(dte + """\n""") e.close() county = 0 if SERVER_STARTED == 0: if set_env() == True: if version_check() == True: try: init_client() log_initialise() SERVER_STARTED = 1 except Exception as e: f.error_logging(APPNAME, str(e), "error_log", "") else: pass else: break time.sleep(1)
def do_inbio_events(terminal_list): function = inspect.stack()[0][3] #first of all get the events, if dont need to do this then dont event_list = inbio_events_into_list() if event_list == -1: return -1 if event_list == 0: return 0 if len(event_list) == 0: return 0 #dont need to do any comms if here for index in range(len(terminal_list)): if terminal_list[index][1] % 100 == 1: ret = send_events(terminal_list[index][0], terminal_list[index][3], event_list) if ret == -1: return -1 #delete all events still at 0 as there were no errors #swap these when ready sqltxt = "DELETE from d_inbio_events WHERE completed = 0" #swap below line with line above if more testing is required. #this means all events will be reset as requiring updating to hardware again and not deleted #sqltxt = "UPDATE d_inbio_events SET completed = 0" ret = sqlconns.sql_command(sqltxt) if ret == -1: f.error_logging(APPNAME, "sql error", "sql", function) return -1 return 0
def set_env(): maindb = 'timeware_main_6' userdb = 'timeware_user_6' if os.path.isfile(gl.GENERAL_INI): fob=open(gl.GENERAL_INI, "r") listme = fob.readlines() fob.close() else: f.error_logging(APPNAME, "Error reading general.ini file.", "error_log","") return False try: for index in range(len(listme)): if "'" in listme[index]: continue if 'server_port' in listme[index]: gl.server_port = int(str.split(listme[index],'=')[1]) if 'https_port' in listme[index]: gl.https_port = int(str.split(listme[index],'=')[1]) if "dbmain" in listme[index]: maindb = str.split(listme[index], '=')[1] maindb = maindb.replace("\r", "") maindb = maindb.replace("\n", "") if "dbuser" in listme[index]: userdb = str.split(listme[index], '=')[1] userdb = userdb.replace("\r", "") userdb = userdb.replace("\n", "") f.error_logging(APPNAME, "Port is now: "+str(gl.server_port), "error_log", "") except Exception as e: f.error_logging(APPNAME, "From SetEnv for loop?:" + e, "error_log", "") return False if sqlconns.readsql_connection_timeware_main_6(maindb,userdb) == 1: test_comms = sqlconns.testsql(gl.SERVER, gl.SQL_LOGIN, gl.PASSWORD, gl.DATABASE) if test_comms == 0: f.error_logging(APPNAME, "Error connecting to SQL server.", "error_log", "") return False return True
def set_env(): if os.path.isfile(gl.SCRIPT_ROOT + 'database.ini'): if sqlconns.readsql_connection_timeware_main_6() == 0: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log", "") return False elif sqlconns.readsql_connection_timeware_main_6() == 1: test_comms = sqlconns.testsql(gl.SERVER, gl.SQL_LOGIN, gl.PASSWORD, gl.DATABASE) if test_comms == 0: f.error_logging(APPNAME, "Error connecting to SQL server.", "error_log", "") return False return True else: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log", "") return False
def log_initialise(): f.error_logging(APPNAME, "Service started.", "error_log", "")
def init_client(): while SERVER_STARTED == 1: f.error_logging(APPNAME, "In Init client.", "error_log", "init_client") #if we get back here we just need to reloop #should only return here when there is a problem but we want to start again none the less ret = main()
def main_function(): f.error_logging(APPNAME, "tested.", "error_log","")
def set_env(): global ACCESS_TERMINAL global ATTENDANCE_TERMINAL global DISTRIBUTOR global OLD_TIME global INBIO_USED global FINGER_DELETION_MINS global FUNCTION_KEYS global IFACE_FUNCTION_KEYS global ORIGINAL_BOOKINGS global CC_FUNCTION_KEYS global MIN_STAMP global MAX_STAMP gl.SERVER = "localhost" gl.SQL_LOGIN = "******" gl.PASSWORD = "******" gl.DATABASE = "timeware_main_6" if os.path.isfile(gl.SCRIPT_ROOT + 'database.ini'): #if sqlconns.readsql_connection_timeware_main_6() == 0: # f.error_logging(APPNAME, "Error reading database.ini file.", "error_log","") # return False if 1 < 0: return elif sqlconns.readsql_connection_timeware_main_6() == 1: gl.SERVER = "localhost" gl.SQL_LOGIN = "******" gl.PASSWORD = "******" gl.DATABASE = "timeware_main_6" test_comms = sqlconns.testsql(gl.SERVER, gl.SQL_LOGIN, gl.PASSWORD, gl.DATABASE) if test_comms == 0: f.error_logging(APPNAME, "Error connecting to SQL server.", "error_log", "") else: if os.path.isfile(gl.GENERAL_INI): fob = open(gl.GENERAL_INI, "r") listme = fob.readlines() fob.close() else: f.error_logging(APPNAME, "Error reading general.ini file.", "error_log", "") return False try: for index in range(len(listme)): if "'" in listme[index]: continue if 'distributor' in listme[index]: DISTRIBUTOR = str.split(listme[index], '=')[1] if 'server_port' in listme[index]: gl.server_port = int( str.split(listme[index], '=')[1]) if 'face_to_personnel' in listme[index]: if 'true' in str.split(listme[index], '=')[1]: gl.face_to_personnel = True if "access_terminal" in listme[index]: ACCESS_TERMINAL = int(listme[index].split("=")[1]) if "attendance_terminal" in listme[index]: ATTENDANCE_TERMINAL = int( listme[index].split("=")[1]) if "fingerprint_deletion" in listme[index]: FINGER_DELETION_MINS = int( listme[index].split("=")[1]) if 'oldtime' in listme[index]: if 'false' in str.split(listme[index], '=')[1]: OLD_TIME = False if "inbio" in listme[index]: if 'true' in str.split(listme[index], '=')[1]: INBIO_USED = True if "s680_function_keys" in listme[index]: if 'true' in str.split(listme[index], '=')[1]: FUNCTION_KEYS = True if "iface_function_keys" in listme[index]: if 'true' in str.split(listme[index], '=')[1]: IFACE_FUNCTION_KEYS = True if "original_bookings" in listme[index]: if 'false' in str.split(listme[index], '=')[1]: ORIGINAL_BOOKINGS = False if "cost_centre_function_keys" in listme[index]: if 'true' in str.split(listme[index], '=')[1]: CC_FUNCTION_KEYS = True if "max_stamp" in listme[index]: MAX_STAMP = str.split(listme[index], '=')[1] if "min_stamp" in listme[index]: MIN_STAMP = str.split(listme[index], '=')[1] except Exception as e: return False return True else: f.error_logging(APPNAME, "Error reading database.ini file.", "error_log", "") return False
def log_exit(): f.error_logging(APPNAME, "iface clean exit", "error_log", "")
import datetime import time import hashlib import win32serviceutil import win32service import win32event import threading import asyncore from thriftpy.rpc import make_client from thriftpy.protocol.binary import TBinaryProtocolFactory from thriftpy.transport import TBufferedTransportFactory from thriftpy.transport import TFramedTransportFactory import gl, sqlconns, functions as f, os, sys f.error_logging(APPNAME, 'we are at the start', 'error_log', "") thrift_file = gl.SCRIPT_ROOT + "zk.thrift" f.error_logging(APPNAME, thrift_file, 'error_log', "") try: zk_thrift = thriftpy.load("zk.thrift", module_name="zk_thrift") except Exception as e: f.error_logging(APPNAME, str(e), 'error_log', "reading thrift file") COMM_ERROR = "communications_log" ERROR_LOG = "error_log" class AppServerSvc(win32serviceutil.ServiceFramework):
def ret_error(ip_address, ret, function): f.error_logging( APPNAME, "Connect failure to " + ip_address + "...(" + str(ret) + ")", ERROR_LOG, function)