def close(self): try: self.connection.shutdown(socket.SHUT_RDWR) except Exception as err: log.error('{}\nfrom {}'.format(err, self.address)) else: log.info('Closed connection for {address}'.format(address=self.address))
def search_host(pre_host=None, port=None, auto=False): # , word=[None, None]): _socket = False if auto: log.info('AUTO MODE') point = time.time() for f in range(0, 255, 4): for i in range(f, f + 4): host = '{}.{}'.format(pre_host, i) assistant_start = threading.Thread(target=check_host, args=(host, port, )) assistant_start.start() index = 0 while index < 4: if not _socket: _socket = SystemQueue.SCQ.get() else: SystemQueue.SCQ.get() index += 1 if _socket: log.info('BREAK') log.info(time.time() - point) log.info(_socket) break else: log.info('MANUAL MODE') check_host(pre_host, port) _socket = SystemQueue.SCQ.get() return _socket
def _f(object_to_check): log.info('{}, args: {}'.format(f_object, object_to_check)) if not ''.join(object_to_check.split('.')).isdigit(): raise Exceptions.FailCheckDigitIP( '{} should contain numbers and dots'.format(object_to_check)) log.info('Function: {}, Status: OK'.format(f_object.__name__)) return f_object(object_to_check)
def _f(object_to_check): log.info('{}, args: {}'.format(f_object, object_to_check)) for segment in object_to_check.split('.'): if int(segment) > 255: raise Exceptions.FailCheckDigitIP('Oops :)') log.info('Function: {}, Status: OK'.format(f_object.__name__)) return f_object(object_to_check)
def _routing_data(self, string): if self.data_callback: log.info('data_callback: {}'.format(self.data_callback)) self.data_callback(string['string']) Thread4Server._send(whom=self.speakThread[string['who']].connection, what='READY TO NEXT') log.info(self.speakThread[string['who']].time) else: log.debug('from {} response {}'.format(string['who'], string['string']))
def _f(object_to_check): log.info('{}, args: {}'.format(f_object, object_to_check)) for segment in object_to_check.split('.'): if len(segment) > 3: raise Exceptions.FailCheckDigitIP( 'Every segment must consist of from one to three digits') log.info('Function: {}, Status: OK'.format(f_object.__name__)) return f_object(object_to_check)
def _get_socket(self): log.info('init search host') _socket = get_socket.search_host(pre_host=self.host, port=self.port, auto=self.auto) log.info(_socket) # self.system_callback({'START': _socket}) return _socket
def check_status(cmd): try: response = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) except Exception as err: log.error(err) return False else: log.info('Response: successfully') return response
def mkdir_for_syslog(dir_name): log.info('mkdir /home/user/{}'.format(dir_name)) try: subprocess.Popen('mkdir /home/user/{}'.format(dir_name), shell=True, stdout=subprocess.PIPE) except Exception as err: log.error(err) else: log.info('mkdir successfully')
def check_host(host=None, port=None, _socket=None): log.info('Connecting to {}:{}:{} ...'.format(host, port, _socket)) try: _socket.connect((host, port)) except Exception as err: log.error('HOST: {} ERROR: {}'.format(host, err)) SystemQueue.SCQ.put(False) else: log.info('Connect :) HOST: {}'.format(host)) _server_identification(host, _socket)
def commit_changes(conn): # Make the changes to the database persistent try: conn.commit() except Exception as err: log.error(err) return False else: log.info('Commit: successfully') return True
def cp_syslog(dir_name): log.info('cp /var/log/syslog /home/user/{}'.format(dir_name)) try: subprocess.Popen('cp /var/log/syslog /home/user/{}'.format(dir_name), shell=True, stdout=subprocess.PIPE) except Exception as err: log.error(err) else: log.info('cp syslog successfully')
def _back_up(self): log.info('BACK-UP running...') self.walkie_talkie_runner = False self.running = False while not CommonQueue.CQ.empty(): data = Sender.__get_from_queue(self) db.insert_into_db(self.db_cursor, time.time(), datetime.now(), data) db.commit_changes(self.db_conn) log.info('BACK-UP: ok')
def run(self): self._init_tcp_server() while self.flag_run: response = CommonQueue.CQ.get() log.info(response) if not isinstance(response, dict): log.error('<{}> must be <dict> type. <{}>'.format(response, type(response))) elif self._get_key(response)[0] in self._get_key(self.queue_handlers): self.queue_handlers[self._get_key(response)[0]](response[self._get_key(response)[0]])
def run(self): while True: try: self.connection, self.address = self.sock.accept() except Exception as err: self.__err_handler('Error accept: {}'.format(err)) break else: log.info("Connection from: " + str(self.address)) # self.check_new_acceptance() self.__handler(self.connection, self.address)
def _f(*object_to_check): log.info('{}, args: {}'.format(f_object, *object_to_check)) # This part of function need for check input parameter that to ensure the safe execution of the function for index, argument in enumerate(inspect.getfullargspec(f_object)[0]): if not isinstance(object_to_check[index], f_object.__annotations__[argument]): raise Exceptions.FailCheckStr( 'object_to_check <{}> must be <str> type'.format( *object_to_check)) log.info('Function: {}, Status: OK'.format(f_object.__name__)) return f_object(*object_to_check)
def run(self): while self.flag_run: try: __connection, __address = self.sock.accept() log.info("Connection from: " + str(__address)) except socket.timeout: pass except Exception as __err: CommonQueue.CQ.put({'accept error': __err}) else: CommonQueue.CQ.put({'acceptance': {'connection': __connection, 'address': __address}}) log.info('SHUTDOWN')
def _f(object_to_check): log.info('{}, args: {}'.format(f_object, object_to_check)) try: sample = object_to_check.split('.') except Exception as err: log.error(err) raise err if len(sample) != 4: raise Exceptions.FailCheckLenIP( 'len({}) must be 4'.format(object_to_check)) log.info('Function: {}, Status: OK'.format(f_object.__name__)) return f_object(object_to_check)
def callback_system(response): global _pause log.info(response) if 'ERROR' in response.keys(): _pause = True elif 'START' in response.keys(): if response['START']: _pause = False else: _pause = True
def _check_args(ip, _port, data_callback, sys_callback, word_for_check_new_acceptance, _run_timer): if checkers.ip(ip) and \ checkers.port(_port) and \ checkers.callback_func(data_callback) and \ checkers.callback_func(sys_callback) and \ checkers.words(word_for_check_new_acceptance) and \ checkers.runner(_run_timer): log.info('GOOD') return True else: log.info('BAD') return False
def _recover(self): back_up_data = db.select_from_db(self.db_cursor, name_table_in_db='data') log.info(back_up_data) for data in back_up_data: log.debug('PUT IN QUEUE {}'.format(data[3])) CommonQueue.CQ.put(data[3], block=False) db.delete_from_table_in_db(self.db_cursor, data[0]) db.commit_changes(self.db_conn) back_up_data = db.select_from_db(self.db_cursor, name_table_in_db='data') log.info(back_up_data) self.system_callback({'START': 'RECOVER DONE'})
def insert_into_head_data(cursor, bat_name, dis, in_sec, in_date): try: cursor.execute("INSERT INTO head_data (" "battery_name, " "discharge_current, " "start_at_in_sec, " "start_at_in_date) VALUES(?, ?, ?, ?)", (bat_name, str(dis), in_sec, in_date)) except Exception as err: log.error(err) return False else: log.info('Insert in table <head_data> {} {} {} {}: successfully'.format(bat_name, str(dis), in_sec, in_date)) return True
def run(self): self.db_init() while self.running: _sender = None _socket = None log.info('host circle. _socket: {}'.format(_socket)) while not _socket: _socket = self._get_socket() self._recover() if _socket: _sender = self._run_sender(_socket) while _socket: _socket = self._get_data_from_server(_socket, _sender)
def create_table_head_data_in_db(cursor): # Execute a command: this creates a new table try: cursor.execute("CREATE TABLE head_data (" "battery_name varchar, " "discharge_current int, " "start_at_in_sec timestamp, " "start_at_in_date timestamp);") except Exception as err: log.error(err) return False else: log.info('Create table <head_data>: successfully') return True
def __init__(self, sender_socket=None, data_callback=None, system_callback=None): log.info('start up') self.running = True self.walkie_talkie_runner = False self.sender_socket = sender_socket self.data_callback = data_callback self.system_callback = system_callback self.db_conn = None self.db_cursor = None threading.Thread.__init__(self)
def insert_into_db(cursor, in_sec, in_date, back_up): try: cursor.execute("INSERT INTO data (" "time_sec, " "time_in_date, " "back_up) VALUES(?, ?, ?)", (in_sec, in_date, back_up)) except Exception as err: log.error(err) return False else: log.info("INSERT INTO data (" "time_sec, " "time_in_date, " "back_up) VALUES({}, {}, {})".format(in_sec, in_date, back_up)) return True
def create_table_in_db(cursor): # Execute a command: this creates a new table try: cursor.execute("CREATE TABLE data (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "time_sec timestamp, " "time_in_date timestamp, " "back_up varchar );") except sqlite3.OperationalError as err: log.info(err) return True except Exception as err: log.error(err) return False else: log.info('Create table <data>: successfully') return True
def _f(*object_to_check): log.info('{}, args: {}'.format(f_object, *object_to_check)) # This part of function need for check input parameter that to ensure the safe execution of the function for index, argument in enumerate(inspect.getfullargspec(f_object)[0]): if object_to_check[index] is not None: if not isinstance(object_to_check[index], f_object.__annotations__[argument]): log.error('object_to_check <{}> must be {f} type'.format( *object_to_check, f=f_object.__annotations__[argument])) return False else: log.error('object_to_check <{}> is <None> type'.format( *object_to_check)) return True log.info('Function: {}, Status: OK'.format(f_object.__name__)) return f_object(*object_to_check)
def _init_tcp_server(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.sock.bind((self.ip, self.port)) except Exception as err: log.error(err) # raise err return False else: self.sock.listen(10) self.sock.setblocking(False) self.sock.settimeout(1) log.info('server start. ip: {} port: {}'.format(self.ip, self.port)) self.acceptThread.sock = self.sock self.acceptThread.start() self.timer.go_go() self.flag_run = True
def _check_to_find(self, _client): if not _client.status: _client.status = True _client.ping = True if self.sys_callback: self.sys_callback('FIND CLIENT <{}> at {} ({})'.format(_client.address, time.time(), datetime.now())) else: self.data_callback('FIND CLIENT <{}> at {} ({})'.format(_client.address, time.time(), datetime.now())) log.info('FIND {}'.format(_client.address)) elif not _client.ping: _client.ping = True if self.sys_callback: self.sys_callback('RECEIVE FROM CLIENT <{}> TEST PING at {} ({})'. format(_client.address, time.time(), datetime.now())) else: self.data_callback('RECEIVE FROM CLIENT <{}> TEST PING at {} ({})'. format(_client.address, time.time(), datetime.now()))