Ejemplo n.º 1
0
                if app.msgst[item]['delaytime'] > max_delay:
                    max_delay = app.msgst[item]['delaytime']
                if app.msgst[item]['delaytime'] < min_delay:
                    min_delay = app.msgst[item]['delaytime']
                total_delay += app.msgst[item]['delaytime']
            else:
                pkg_lost += 1
                pkg_lost_list.append(item)

        LOG.info('Total package: %d' % len(app.msgst))
        if pkg_lost_list:
            LOG.error('Package with these ids have lost:')
            for i in pkg_lost_list:
                LOG.warn('%d' % i)
        LOG.error('Loss Rate: ' + "%.2f" %
                  (pkg_lost * 100.0 / arg_handle.get_args('number_to_send')) +
                  '%')
        LOG.info('MAX delay time: %dms' % max_delay)
        LOG.yinfo('MIN delay time: %dms' % min_delay)
        LOG.info('Average delay time(%d / %d): %.2fms' %
                 (total_delay, (len(app.msgst) - pkg_lost),
                  (total_delay + 0.0) / (len(app.msgst) - pkg_lost)))

    except KeyboardInterrupt:
        LOG.info('KeyboardInterrupt!')
        sys.exit()

    except Exception as e:
        LOG.error('something wrong!' + str(e))
        sys.exit()
Ejemplo n.º 2
0
class Task():
    def __init__(self, name='default-task', logger=None):
        self.tasks = {}
        self.lock = threading.RLock()
        if logger:
            self.LOG = logger
        else:
            self.LOG = MyLogger(name + '.log', clevel=logging.DEBUG)
        self.need_stop = False

    def stop(self):
        self.need_stop = True
        self.LOG.warn('Thread %s stoped!' % (__name__))

    def add_task(self, name, func, run_times=1, interval=5, *argv):
        self.lock.acquire()
        if name and func and int(run_times) >= 1 and int(interval) >= 1:
            pass
        else:
            self.LOG.error("Invalid task: %s, run_times: %d, internal: %d" %
                           (name, int(run_times), int(interval)))
        self.LOG.info("To add task: %s, run_times: %d, internal: %d" %
                      (name, int(run_times), int(interval)))
        self.tasks[name] = {
            'func': func,
            'run_times': int(run_times),
            'interval': int(interval),
            'now_seconds': 0,
            'argv': argv,
            'state': 'active',
            'name': name
        }
        self.lock.release()

    def del_task(self, name):
        self.lock.acquire()
        self.LOG.warn("To delete task:%s" % (name))
        if name in self.tasks:
            del self.tasks[name]
        self.lock.release()

    def show_tasks(self):
        if self.tasks:
            for task in self.tasks:
                self.LOG.info(task + ":")
                for item in sorted(self.tasks[task]):
                    self.LOG.yinfo("    " + item.ljust(20) + ':' +
                                   str(self.tasks[task][item]).rjust(20))
        else:
            self.LOG.warn("No task...")

    def task_proc(self):
        while self.need_stop == False:
            if len(self.tasks) == 0:
                self.LOG.debug("No task!\n")
            '''
            for task in self.tasks:
                if self.tasks[task]['state'] == 'inactive':
                    self.del_task(task)
            '''
            try:
                self.lock.acquire()
                for task in self.tasks:
                    if self.tasks[task]['state'] != 'active':
                        continue
                    self.tasks[task]['now_seconds'] += 1
                    if self.tasks[task]['now_seconds'] >= self.tasks[task][
                            'interval']:
                        if callable(self.tasks[task]['func']):
                            # self.LOG.info("It is time to run %s: " % (
                            #    task) + self.tasks[task]['func'].__name__ + str(self.tasks[task]['argv']))
                            self.tasks[task]['func'](
                                *(self.tasks[task]['argv']))
                        elif callable(eval(self.tasks[task]['func'])):
                            # self.LOG.info("It is time to run %s: " % (
                            #    task) + self.tasks[task]['func'] + str(self.tasks[task]['argv']))
                            eval(self.tasks[task]['func'] + '(*' +
                                 str(self.tasks[task]['argv']) + ')')
                        else:
                            self.LOG.error(
                                "Uncallable task: %s, will disable it!")
                            self.tasks[task]['state'] = 'inactive'
                        self.tasks[task]['now_seconds'] = 0
                        self.tasks[task]['run_times'] -= 1
                        if self.tasks[task]['run_times'] == 0:
                            self.LOG.info("stop task:%s" % (task))
                            self.tasks[task]['state'] = 'inactive'
                    else:
                        pass
                self.lock.release()
                time.sleep(0.1)

            except RuntimeError:
                pass
Ejemplo n.º 3
0
    # cmd arg init
    arg_handle = ArgHandle()
    arg_handle.run()

    # sys init
    sys_init()

    # multi thread
    global thread_list
    thread_list = []

    # create clients
    clients = []
    for i in range(1, arg_handle.get_args('client_count') + 1):
        LOG.yinfo('To create client: %d' % (i))
        sim = AirControl(('192.168.10.1', 5100), logger=LOG)
        thread_list.append([sim.schedule_loop])
        thread_list.append([sim.send_data_loop])
        thread_list.append([sim.heartbeat_loop])

    # run threads
    sys_proc()
    # sys_join()

    # cmd loop
    signal.signal(signal.SIGINT, lambda signal,
                  frame: cprint.notice_p('Exit SYSTEM: exit'))
    my_cmd = MyCmd()
    my_cmd.cmdloop()