Esempio n. 1
0
    def __init__(self, bencoded_msg):
        try:
            self._msg_dict = bencode.decode(bencoded_msg)
        except (bencode.DecodeError):
            log.exception('invalid bencode')
            raise MsgError, 'invalid bencode'
        # Make sure the decoded data is a dict and has a TID key
        try:
            self.tid = self._msg_dict[TID]
        except (TypeError):
            raise MsgError, 'decoded data is not a dictionary'
        except (KeyError): 
            raise MsgError, 'key TID not found'
        # Sanitize TID
        if not (isinstance(self.tid, str) and self.tid):
            raise MsgError, 'TID must be a non-empty binary string'

        # Sanitize TYPE
        try:
            self.type = self._msg_dict[TYPE]
        except (KeyError):
            raise MsgError, 'key TYPE not found'

        if not self.type in (QUERY, RESPONSE, ERROR):
            raise MsgError, 'Unknown TYPE value'
        if self.type == QUERY:
            self._sanitize_query()
        elif self.type == ERROR:
            self._sanitize_error()
        return
Esempio n. 2
0
def encode(data):
    output = cStringIO.StringIO()
    try:
        encode_f[type(data)](data, output)
    except (KeyError):
        log.exception('Data: %s' % data)
        raise EncodeError, 'see ERROR log'
    result = output.getvalue()
    output.close()
    return result
Esempio n. 3
0
 def __finiModules(self):
     """
     Finish module operation.
     """
     for subWin in self.mdiArea.subWindowList():
         module = subWin.widget()
         if isinstance(module, AppMod):
             try:
                 module.fini()
             except Exception as e:
                 log.exception(e)
Esempio n. 4
0
 def __loadSystemSetting(self):
     """
     Load system settings and restore these settings.
     """
     try:
         pos = consttype.SysSetting.value("position")
         size = consttype.SysSetting.value("size")
         self.resize(size)
         self.move(pos)
     except Exception as e:
         log.exception(e)
Esempio n. 5
0
def report(roster, cli, config):
    '''Print a human-friendly report about a time-slice of the roster.'''
    time_zone = config['roster.time_zone']
    # We use datetimes even if the ultimate goal is operate at date level as
    # we need to preserve the timezone information all along
    fuzzy = cli['<fuzzy>']
    # Fuzzy should be interpreted as always indicating a month.
    if fuzzy:
        try:
            start = fuzzy.replace(day=1)
            end = start + relativedelta(months=1, days=-1)
        except Exception as e:
            log.critical('Cannot parse <fuzzy> parameter "{}"'.format(fuzzy))
            log.exception(e.message)
            raise
    # A range can be whatever
    elif cli['<start>']:
        start = cli['<start>']
        end = cli['<end>']
        if start > end:
            msg = 'Tried to generate a report for negative timespan ({} to {})'
            log.critical(msg.format(start, end))
            exit(os.EX_DATAERR)
    else:
        now = datetime.datetime.now(tz=pytz.timezone(time_zone))
        start = now.replace(day=1) + relativedelta(months=-1)
        end = start + relativedelta(months=1, days=-1)
    data = roster.report(start, end)
    weekdays = defaultdict(int)
    weekends = defaultdict(int)
    for day, people in data:
        target = weekdays if day.weekday() < 5 else weekends
        for person in people:
            target[person] += 1
    print('\n             O N - C A L L   R O S T E R')
    print('=====================================================')
    print('              {} - {}\n\n'.format(start.strftime('%d %b %Y'),
                                             end.strftime('%d %b %Y')))
    for row in data:
        print('  {:<20}{}'.format(row[0].strftime('%d %b %Y, %a'),
                                  ', '.join(row[1])))
    print('\n\n                      SUMMARY')
    print('-----------------------------------------------------')
    print('  Name                    Weekdays  Weekends  Total')
    print('-----------------------------------------------------')
    names = sorted(list(set(weekends.keys() + weekdays.keys())))
    template = '  {:<26}{:>3}{:>10}{:>8}'
    for name in names:
        wd = weekdays[name]
        we = weekends[name]
        print(template.format(name, wd or '-', we or '-', wd + we))
    print('-----------------------------------------------------\n')
 def on_query_received(self, query_msg, addr):
     log.debug('query received\n%s\nSource: %s' % (`query_msg`,
                                                       `addr`))
     try:
         handler = self.query_handler[query_msg.query]
     except (KeyError, ValueError):
         log.exception('Invalid QUERY')
         return # ignore query #TODO2: send error back?
     response_msg = handler(query_msg)
     self.notify_routing_m_on_query(node.Node(addr,
                                              query_msg.sender_id,
                                              query_msg.ns_node))
     return response_msg
Esempio n. 7
0
    def loadConf(self):
        """
        @override
        Load persisted config values
        """
        with open(self._filename, 'rb') as f:
            try:
                conf = pickle.load(f)
            except EOFError as e:
                log.exception(e)
            else:
                self._conf = conf

            self._mergeDefConf()
Esempio n. 8
0
 def on_response_received(self, response_msg):
     try:
         response_msg.sanitize_response(self.query)
     except (message.MsgError):
         log.exception(
             "We don't like dirty reponses: %r|nresponse ignored"
             % response_msg)
         return # Response ignored 
     self.node.is_ns = response_msg.ns_node
     if self.node.id:
         if response_msg.sender_id != self.node.id:
             return # Ignore response
     else:
         self.node.id = response_msg.sender_id
     #TODO2: think whether late responses should be accepted
     if self.timeout_task.cancelled:
         log.warning(
             "Response recevived but it's too late!!\n%r, %r" %
             (response_msg,
             self.timeout_task))
         return # Ignore response
     self.timeout_task.cancel()
     nodes = []
     try:
         nodes.extend(response_msg.nodes)
     except (AttributeError):
         pass
     try:
         nodes.extend(response_msg.nodes2)
     except (AttributeError):
         pass
     # Notify routing manager (if nodes found).
     # Do not notify when the query was a GET_PEERS because
     # the lookup is in progress and the routing_m shouldn't
     # generate extra traffic.
     if self.query == message.FIND_NODE and \
             nodes and self.notify_routing_m_on_nodes_found_f:
         self.notify_routing_m_on_nodes_found_f(nodes)
     # Notify routing manager (response)
     self.node.is_ns = response_msg.ns_node
     if self.notify_routing_m_on_response_f:
         self.notify_routing_m_on_response_f(self.node)
     # Do callback to whomever did the query
     self.on_response_f(response_msg, self.node)
     return True # the response was fine
    def run(self):
        """Main loop activated by calling self.start()"""
        
        last_task_run = time.time()
        stop_flag = self.stop_flag
        while not stop_flag:
            timeout_raised = False
            try:
                data, addr = self.s.recvfrom(BUFFER_SIZE)
            except (AttributeError):
                log.warning('udp_listen has not been called')
                time.sleep(self.task_interval)
                #TODO2: try using Event and wait
                timeout_raised = True
            except (socket.timeout):
                timeout_raised = True
            except (socket.error), e:
                log.critical(
                    'Got socket.error when receiving (more info follows)')
                log.exception('See critical log above')
            else:
                ip_is_blocked = self.floodbarrier_active and \
                                self.floodbarrier.ip_blocked(addr[0])
                if ip_is_blocked:
                    log.warning('%s blocked' % `addr`)
                else:
                    self.datagram_received_f(data, addr)

            if timeout_raised or \
                   time.time() - last_task_run > self.task_interval:
                #with self._lock:
                self._lock.acquire()
                try:
                    while True:
                        task = self.tasks.consume_task()
                        if task is None:
                            break
                        task.fire_callbacks()
                    stop_flag = self.stop_flag
                finally:
                    self._lock.release()
 def sendto(self, data, addr):
     """Send data to addr using the UDP port used by listen_udp."""
     #with self._lock:
     self._lock.acquire()
     try:
         try:
             bytes_sent = self.s.sendto(data, addr)
             if bytes_sent != len(data):
                 log.critical(
                     'Just %d bytes sent out of %d (Data follows)' % (
                         bytes_sent,
                         len(data)))
                 log.critical('Data: %s' % data)
         except (socket.error):
             log.critical(
                 'Got socket.error when sending (more info follows)')
             log.critical('Sending data to %r\n%r' % (addr,
                                                          data))
             log.exception('See critical log above')
     finally:
         self._lock.release()
Esempio n. 11
0
    def __createAppMod(self, modCls):
        """
        Create module.
        """
        if issubclass(modCls, AppQtMod):                    # AppQtMod instance
            if modCls.__name__ in self.__modSubWin.keys():
                subWin = self.__modSubWin[modCls.__name__]

            else:
                try:
                    module = modCls()
                    if module.init():
                        subWin = self.__addSubWin(module)
                except Exception as e:
                    log.exception(e)
                    self.__delSubWin(modCls)
                    return

            if subWin != self.mdiArea.activeSubWindow():
                self.mdiArea.setActiveSubWindow(subWin)

            subWin.showMaximized()
Esempio n. 12
0
        def execute_endpoint(*args, **kwargs):
            log.debug("{0} {1}{2}".format(
                flask.request.method,
                flask.request.url_rule.rule,
                "?" + flask.request.query_string if flask.request.query_string else ""
            ))

            try:
                obj = self.execute_endpoint_inner(endpoint, *args, **kwargs)
                if not obj: obj = ApiObject()
                obj.code = httplib.OK
                obj.msg = None

            except self.Error as error:
                obj = ApiObject()
                obj.code = error.code
                obj.msg = error.msg
                log.exception(obj.msg)

            except:
                obj = ApiObject()
                obj.code = httplib.INTERNAL_SERVER_ERROR
                obj.msg = None
                log.exception(obj.msg)

            obj.msg = obj.msg if obj.msg else httplib.responses[obj.code]

            data = obj.encode()

            self.dump("response:\n{0}".format(data))

            response = flask.Response(
                data,
                obj.code,
                headers=None,
                mimetype="application/json"
            )

            return response