Пример #1
0
 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))
Пример #2
0
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
Пример #3
0
 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)
Пример #4
0
 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)
Пример #5
0
 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']))
Пример #6
0
 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)
Пример #7
0
    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
Пример #8
0
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
Пример #9
0
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')
Пример #10
0
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)
Пример #11
0
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
Пример #12
0
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')
Пример #13
0
 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')
Пример #14
0
    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]])
Пример #15
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)
Пример #16
0
 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)
Пример #17
0
 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')
Пример #18
0
 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)
Пример #19
0
    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
Пример #20
0
 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
Пример #21
0
 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'})
Пример #22
0
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
Пример #23
0
 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)
Пример #24
0
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
Пример #25
0
    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)
Пример #26
0
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
Пример #27
0
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
Пример #28
0
 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)
Пример #29
0
 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
Пример #30
0
 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()))