コード例 #1
0
 def isConnectionAlive(self, *args, **kwargs):
     # miss = 0
     if driver.is_on('service_udp_datagrams'):
         from lib import udp
         if time.time() - udp.get_last_datagram_time() < 60:
             if settings.enableUDP() and settings.enableUDPreceiving():
                 return True
     # else:
     #     miss += 1
     if driver.is_on('service_gateway'):
         from transport import gateway
         if time.time() - gateway.last_inbox_time() < 60:
             return True
         transport_states = [
             t.state for t in list(gateway.transports().values())
         ]
         if 'LISTENING' in transport_states:
             return True
         if 'STARTING' in transport_states:
             return True
     # else:
     #     miss += 1
     # if miss >= 2:
     #     return True
     # return False ... still testing that approach
     return True
コード例 #2
0
 def isConnectionAlive(self, arg):
     # miss = 0
     if driver.is_on('service_udp_datagrams'):
         from lib import udp
         if time.time() - udp.get_last_datagram_time() < 60:
             if settings.enableUDP() and settings.enableUDPreceiving():
                 return True
     # else:
     #     miss += 1
     if driver.is_on('service_gateway'):
         from transport import gateway
         if time.time() - gateway.last_inbox_time() < 60:
             return True
         transport_states = map(lambda t: t.state,
                                gateway.transports().values())
         if 'LISTENING' in transport_states:
             return True
         if 'STARTING' in transport_states:
             return True
     # else:
     #     miss += 1
     # if miss >= 2:
     #     return True
     return True  # testing
     return False
コード例 #3
0
 def doSetUp(self, *args, **kwargs):
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.doSetUp')
     if driver.is_on('service_udp_datagrams'):
         from lib import udp
         udp_port = settings.getUDPPort()
         if not udp.proto(udp_port):
             try:
                 udp.listen(udp_port)
             except:
                 lg.exc()
     if driver.is_on('service_service_entangled_dht'):
         from dht import dht_service
         dht_service.reconnect()
     if driver.is_on('service_ip_port_responder'):
         from stun import stun_server
         udp_port = int(settings.getUDPPort())
         stun_server.A('start', udp_port)
     if driver.is_on('service_my_ip_port'):
         from stun import stun_client
         if not stun_client.A() or stun_client.A().state in ['STOPPED', ]: 
             stun_client.A().dropMyExternalAddress()
             stun_client.A('start')
     if driver.is_on('service_private_messages'):
         from chat import nickname_holder
         nickname_holder.A('set')
     self.automat('network-up')
コード例 #4
0
 def doSetUp(self, arg):
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.doSetUp')
     # if driver.is_on('service_identity_server'):
     #     if settings.enableIdServer():
     #         from userid import id_server
     #         id_server.A('start', (settings.getIdServerWebPort(),
     #                               settings.getIdServerTCPPort()))
     if driver.is_on('service_service_entangled_dht'):
         from dht import dht_service
         dht_service.reconnect()
     if driver.is_on('service_ip_port_responder'):
         from stun import stun_server
         udp_port = int(settings.getUDPPort())
         stun_server.A('start', udp_port)
     if driver.is_on('service_my_ip_port'):
         from stun import stun_client
         stun_client.A().dropMyExternalAddress()
         stun_client.A('start')
     if driver.is_on('service_private_messages'):
         from chat import nickname_holder
         nickname_holder.A('set', None)
     # if driver.is_on('service_gateway'):
     #     from transport import gateway
     #     gateway.start()
     self.automat('network-up')
コード例 #5
0
def contacts(include_all=False, include_enabled=True):
    """
    Return a union of suppliers and customers ID's.
    """
    result = set()
    if include_all or (include_enabled and driver.is_enabled('service_customer')) or driver.is_on('service_customer'):
        result.update(set(suppliers()))
    if include_all or (include_enabled and driver.is_enabled('service_supplier')) or driver.is_on('service_supplier'):
        result.update(set(customers()))
    if include_all or (include_enabled and driver.is_enabled('service_private_messages')) or driver.is_on('service_private_messages'):
        result.update(set(correspondents_ids()))
    return list(result)
コード例 #6
0
 def doSetDown(self, arg):
     """
     """
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.doSetDown')
     if driver.is_on('service_service_entangled_dht'):
         from dht import dht_service
         dht_service.disconnect()
     if driver.is_on('service_ip_port_responder'):
         from stun import stun_server
         stun_server.A('stop')
     if driver.is_on('service_gateway'):
         from transport import gateway
         gateway.stop()
     self.automat('network-down')
コード例 #7
0
    def doSetUp(self, arg):
        if _Debug:
            lg.out(_DebugLevel, 'network_connector.doSetUp')

#         Second attempt
#         l = []
#         for service_name in driver.affecting('service_network'):
#             d = driver.start_single(service_name)
#             l.append(d)
#
#         def _ok(x):
#             lg.info('network child services is UP')
#             self.automat('network-up')
#             return None
#
#         def _fail(err):
#             lg.err(err)
#             self.automat('network-up')
#             return None
#
#         dl = DeferredList(l, fireOnOneErrback=True, consumeErrors=True)
#         dl.addCallback(_ok)
#         d.addErrback(_fail)

# First Solution
        if driver.is_on('service_service_entangled_dht'):
            from dht import dht_service
            dht_service.reconnect()
        if driver.is_on('service_ip_port_responder'):
            from stun import stun_server
            udp_port = int(settings.getUDPPort())
            stun_server.A('start', udp_port)
        if driver.is_on('service_my_ip_port'):
            from stun import stun_client
            stun_client.A().dropMyExternalAddress()
            stun_client.A('start')
        if driver.is_on('service_private_messages'):
            from chat import nickname_holder
            nickname_holder.A('set')
        if driver.is_on('service_udp_datagrams'):
            from lib import udp
            udp_port = settings.getUDPPort()
            if not udp.proto(udp_port):
                try:
                    udp.listen(udp_port)
                except:
                    lg.exc()
        self.automat('network-up')
コード例 #8
0
 def start(self):
     from logs import lg
     from transport import callback
     from main import events
     from contacts import contactsdb
     from storage import accounting
     from services import driver
     from supplier import customer_space
     callback.append_inbox_callback(self._on_inbox_packet_received)
     events.add_subscriber(customer_space.on_identity_url_changed, 'identity-url-changed')
     events.add_subscriber(customer_space.on_customer_accepted, 'existing-customer-accepted')
     events.add_subscriber(customer_space.on_customer_accepted, 'new-customer-accepted')
     events.add_subscriber(customer_space.on_customer_terminated, 'existing-customer-denied')
     events.add_subscriber(customer_space.on_customer_terminated, 'existing-customer-terminated')
     space_dict, _ = accounting.read_customers_quotas()
     for customer_idurl in contactsdb.customers():
         known_customer_meta_info = contactsdb.get_customer_meta_info(customer_idurl)
         events.send('existing-customer-accepted', data=dict(
             idurl=customer_idurl,
             allocated_bytes=space_dict.get(customer_idurl.to_bin()),
             ecc_map=known_customer_meta_info.get('ecc_map'),
             position=known_customer_meta_info.get('position'),
         ))
     if driver.is_on('service_entangled_dht'):
         self._do_connect_suppliers_dht_layer()
     else:
         lg.warn('service service_entangled_dht is OFF')
     events.add_subscriber(self._on_dht_layer_connected, event_id='dht-layer-connected')
     return True
コード例 #9
0
 def isAllTransportsReady(self, arg):
     """
     Condition method.
     """
     if not driver.is_on('service_gateway'):
         return False
     LISTENING_count = 0
     OFFLINE_count = 0
     from transport import gateway
     transports = gateway.transports().values()
     for t in transports:
         if t.state != 'OFFLINE' and t.state != 'LISTENING':
             return False
         if t.state == 'OFFLINE':
             OFFLINE_count += 1
         if t.state == 'LISTENING':
             LISTENING_count += 1
     if _Debug:
         lg.out(
             _DebugLevel,
             'network_connector.isAllTransportsReady returning True : all transports READY : HELLO WORLD!!! '
         )
         lg.out(
             _DebugLevel,
             '    OFFLINE transports:%d, LISTENING transports: %d' %
             (OFFLINE_count, LISTENING_count))
     return True
コード例 #10
0
 def state_changed(self, oldstate, newstate, event, arg):
     global_state.set_global_state('NETWORK ' + newstate)
     if driver.is_on('service_p2p_hookups'):
         from p2p import p2p_connector
         from system import tray_icon
         p2p_connector.A('network_connector.state', newstate)
         tray_icon.state_changed(self.state, p2p_connector.A().state)
コード例 #11
0
 def doRestartCustomersRejector(self, arg):
     """
     Action method.
     """
     if driver.is_on('service_customer_patrol'):
         from supplier import customers_rejector
         customers_rejector.A('restart')
コード例 #12
0
 def doRestartBackupMonitor(self, arg):
     """
     Action method.
     """
     if driver.is_on('service_backup_monitor'):
         from storage import backup_monitor
         backup_monitor.A('restart')
コード例 #13
0
def on_tray_icon_command(cmd):
    from main import shutdowner
    from services import driver
    from p2p import network_connector
    lg.out(2, 'on_tray_icon_command %s' % cmd)
    if cmd == 'exit':
        # SendCommandToGUI('exit')
        shutdowner.A('stop', 'exit')

    elif cmd == 'restart':
        # SendCommandToGUI('exit')
        appList = bpio.find_process(['bpgui.', ])
        if len(appList) > 0:
            shutdowner.A('stop', 'restartnshow')  # ('restart', 'show'))
        else:
            shutdowner.A('stop', 'restart')  # ('restart', ''))

    elif cmd == 'reconnect':
        if driver.is_on('service_network'):
            network_connector.A('reconnect')

    elif cmd == 'show':
        show()

    elif cmd == 'hide':
        pass
        # SendCommandToGUI('exit')

    elif cmd == 'toolbar':
        pass
        # SendCommandToGUI('toolbar')

    else:
        lg.warn('wrong command: ' + str(cmd))
コード例 #14
0
 def start(self):
     from twisted.internet.defer import Deferred
     from logs import lg
     from main.config import conf
     from main import events
     from raid import eccmap
     from services import driver
     from customer import fire_hire
     self.starting_deferred = Deferred()
     self.starting_deferred.addErrback(
         lambda err: lg.warn('service %r was not started: %r' %
                             (self.service_name, err.getErrorMessage()
                              if err else 'unknown reason')))
     self.all_suppliers_hired_event_sent = False
     if driver.is_on('service_entangled_dht'):
         self._do_join_suppliers_dht_layer()
     eccmap.Update()
     fire_hire.A('init')
     fire_hire.A().addStateChangedCallback(self._on_fire_hire_ready, None,
                                           'READY')
     conf().addConfigNotifier('services/customer/suppliers-number',
                              self._on_suppliers_number_modified)
     conf().addConfigNotifier('services/customer/needed-space',
                              self._on_needed_space_modified)
     events.add_subscriber(self._on_supplier_modified, 'supplier-modified')
     events.add_subscriber(self._on_dht_layer_connected,
                           event_id='dht-layer-connected')
     if fire_hire.IsAllHired():
         self.starting_deferred.callback(True)
         self.starting_deferred = None
         lg.info('all my suppliers are already hired')
         return True
     fire_hire.A('restart')
     return self.starting_deferred
コード例 #15
0
 def doInit(self, *args, **kwargs):
     """
     Action method.
     """
     self._do_block_rebuilding()
     self.known_suppliers = [
         _f
         for _f in contactsdb.suppliers(customer_idurl=self.customer_idurl)
         if _f
     ]
     if not self.EccMap:
         if self.customer_idurl == my_id.getIDURL():
             self.EccMap = eccmap.Current()
             lg.info('ECC map %r set from local for my own suppliers' %
                     self.EccMap)
     if not self.EccMap:
         known_eccmap_dict = {}
         for supplier_idurl in self.known_suppliers:
             known_ecc_map = contactsdb.get_supplier_meta_info(
                 supplier_idurl=supplier_idurl,
                 customer_idurl=self.customer_idurl,
             ).get('ecc_map', None)
             if known_ecc_map:
                 if known_ecc_map not in known_eccmap_dict:
                     known_eccmap_dict[known_ecc_map] = 0
                 known_eccmap_dict[known_ecc_map] += 1
         if known_eccmap_dict:
             all_known_eccmaps = list(known_eccmap_dict.items())
             all_known_eccmaps.sort(key=lambda i: i[1], reverse=True)
             self.EccMap = eccmap.eccmap(all_known_eccmaps[0][0])
             lg.info('ECC map %r recognized from suppliers meta info' %
                     self.EccMap)
         else:
             known_ecc_map = None
             if driver.is_on('service_shared_data'):
                 from access import shared_access_coordinator
                 active_share = shared_access_coordinator.get_active_share(
                     self.key_id)
                 if active_share:
                     known_ecc_map = active_share.known_ecc_map
             if known_ecc_map:
                 self.EccMap = eccmap.eccmap(known_ecc_map)
                 lg.info('ECC map %r recognized from active share %r' % (
                     self.EccMap,
                     active_share,
                 ))
             else:
                 num_suppliers = len(self.known_suppliers)
                 if num_suppliers not in eccmap.GetPossibleSuppliersCount():
                     num_suppliers = settings.DefaultDesiredSuppliers()
                 self.EccMap = eccmap.eccmap(
                     eccmap.GetEccMapName(num_suppliers))
                 lg.warn(
                     'no meta info found, guessed ECC map %r from %d known suppliers'
                     % (self.EccMap, len(self.known_suppliers)))
     self.max_errors = eccmap.GetCorrectableErrors(
         self.EccMap.NumSuppliers())
     if data_receiver.A():
         data_receiver.A().addStateChangedCallback(
             self._on_data_receiver_state_changed)
コード例 #16
0
 def _on_my_identity_url_changed(self, evt):
     from services import driver
     if driver.is_on('service_entangled_dht'):
         from dht import dht_service
         from userid import my_id
         if my_id.getIDURL():
             dht_service.set_node_data('idurl', my_id.getIDURL().to_text())
コード例 #17
0
 def _on_request_service_received(self, newpacket, info):
     from twisted.internet.defer import Deferred
     from logs import lg
     from lib import serialization
     from services import driver
     from p2p import p2p_service
     from transport import packet_out
     if len(newpacket.Payload) > 1024 * 10:
         lg.warn('too long payload')
         p2p_service.SendFail(newpacket, 'too long payload')
         return False
     try:
         json_payload = serialization.BytesToDict(newpacket.Payload,
                                                  keys_to_text=True,
                                                  values_to_text=True)
         json_payload['name']
         json_payload['payload']
     except:
         lg.warn('json payload invalid')
         p2p_service.SendFail(newpacket, 'json payload invalid')
         return False
     service_name = str(json_payload['name'])
     lg.out(
         self.debug_level,
         "service_p2p_hookups.RequestService {%s} from %s" % (
             service_name,
             newpacket.OwnerID,
         ))
     if not driver.is_exist(service_name):
         lg.warn("got wrong payload in %s" % service_name)
         p2p_service.SendFail(newpacket,
                              'service %s not exist' % service_name)
         return False
     if not driver.is_on(service_name):
         p2p_service.SendFail(newpacket, 'service %s is off' % service_name)
         return False
     try:
         result = driver.request(service_name, json_payload['payload'],
                                 newpacket, info)
     except:
         lg.exc()
         p2p_service.SendFail(newpacket,
                              'request processing failed with exception')
         return False
     if not result:
         lg.out(
             self.debug_level,
             "service_p2p_hookups._send_request_service SKIP request %s" %
             service_name)
         return False
     if isinstance(result, Deferred):
         lg.out(
             self.debug_level,
             "service_p2p_hookups._send_request_service fired delayed execution"
         )
     elif isinstance(result, packet_out.PacketOut):
         lg.out(
             self.debug_level,
             "service_p2p_hookups._send_request_service outbox packet sent")
     return True
コード例 #18
0
    def doVerifyTransports(self, *args, **kwargs):
        """
        Action method.
        """
        if not driver.is_on('service_gateway'):
            self.automat('gateway-is-not-started')
            return
        from transport import gateway

        def _transports_verified(all_results):
            if _Debug:
                lg.out(
                    _DebugLevel,
                    'network_connector._transports_verified : %s' %
                    str(all_results))
            order, all_results = all_results
            not_valid_count = 0
            restarts_count = 0
            if len(order) == 0:
                self.automat('network-transports-verified')
                return
            for proto in order:
                if not all_results[proto]:
                    not_valid_count += 1
            for priority in range(len(order)):
                proto = order[priority]
                if not all_results[proto]:
                    if _Debug:
                        lg.out(
                            _DebugLevel,
                            '    [%s] at position %d needs restart' %
                            (proto, priority))
                    gateway.transport(proto).automat('restart')
                    restarts_count += 1
                    if not_valid_count > 1:  # this one failed, 2 other failed as well
                        self.automat('network-transports-verified')
                        return
                    continue
                if not_valid_count > 0:
                    if _Debug:
                        lg.out(
                            _DebugLevel,
                            '    skip %d transport [%s]' % (priority, proto))
                    if restarts_count == 0:
                        if _Debug:
                            lg.out(
                                _DebugLevel,
                                '    but no restarts and %d:[%s] is valid' %
                                (priority, proto))
                        self.automat('network-transports-verified')
                    return
                if _Debug:
                    lg.out(
                        _DebugLevel,
                        '        [%s] at position %d is fine, skip other transports'
                        % (proto, priority))
                self.automat('network-transports-verified')
                return

        gateway.verify().addCallback(_transports_verified)
コード例 #19
0
 def isAllReady(self, *args, **kwargs):
     """
     Condition method.
     """
     if not driver.is_on('service_gateway'):
         if _Debug:
             lg.out(_DebugLevel, 'network_connector.isAllReady returning False : service_gateway is OFF')
         return False
     LISTENING_count = 0
     OFFLINE_count = 0
     from transport import gateway
     transports = list(gateway.transports().values())
     for t in transports:
         if t.state != 'OFFLINE' and t.state != 'LISTENING':
             if _Debug:
                 lg.out(_DebugLevel, 'network_connector.isAllReady returning False : transport %s is not READY yet' % t)
             return False
         if t.state == 'OFFLINE':
             OFFLINE_count += 1
         if t.state == 'LISTENING':
             LISTENING_count += 1
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.isAllReady returning True : all transports READY')
         lg.out(_DebugLevel, '    OFFLINE transports:%d, LISTENING transports: %d' % (OFFLINE_count, LISTENING_count))
     return True
コード例 #20
0
 def start(self):
     from twisted.internet import reactor  # @UnresolvedImport
     from twisted.internet.defer import Deferred
     from logs import lg
     from transport.proxy import proxy_interface
     from transport import network_transport
     from transport import gateway
     from services import driver
     from main import events
     from main.config import conf
     if len(self._available_transports()) == 0:
         lg.warn('no transports available')
         return False
     events.add_subscriber(self._on_dht_layer_connected,
                           'dht-layer-connected')
     self._check_reset_original_identity()
     self.starting_deferred = Deferred()
     self.transport = network_transport.NetworkTransport(
         'proxy', proxy_interface.GateInterface())
     conf().addConfigNotifier('services/proxy-transport/enabled',
                              self._on_enabled_disabled)
     conf().addConfigNotifier('services/proxy-transport/sending-enabled',
                              self._on_sending_enabled_disabled)
     conf().addConfigNotifier('services/proxy-transport/receiving-enabled',
                              self._on_receiving_enabled_disabled)
     if driver.is_on('service_entangled_dht'):
         self._do_join_proxy_routers_dht_layer()
     else:
         self.transport.automat(
             'init', (gateway.listener(), self._on_transport_state_changed))
         reactor.callLater(0, self.transport.automat,
                           'start')  # @UndefinedVariable
     return self.starting_deferred
コード例 #21
0
ファイル: p2p_connector.py プロジェクト: StasEvseev/devel
 def doRestartFireHire(self, *args, **kwargs):
     """
     Action method.
     """
     if driver.is_on('service_employer'):
         from customer import fire_hire
         fire_hire.A('restart')
コード例 #22
0
 def isAllListening(self, *args, **kwargs):
     """
     Condition method.
     """
     if not driver.is_on('service_gateway'):
         if _Debug:
             lg.out(
                 _DebugLevel,
                 'network_connector.isAllListening returning False : service_gateway is OFF'
             )
         return False
     from transport import gateway
     transports = list(gateway.transports().values())
     for t in transports:
         if t.state != 'LISTENING':
             if _Debug:
                 lg.out(
                     _DebugLevel,
                     'network_connector.isAllListening returning False : transport %s is not LISTENING'
                     % t)
             return False
     if _Debug:
         lg.out(_DebugLevel,
                'network_connector.isAllListening returning True')
     return True
コード例 #23
0
ファイル: message_keeper.py プロジェクト: riyazudheen/devel
def backup_outgoing_message(private_message_object, message_id):
    """
    """
    if not driver.is_on('service_backups'):
        lg.warn('service_backups is not started')
        return False
    serialized_message = private_message_object.serialize()
    local_msg_folder = os.path.join(settings.ChatChannelsDir(),
                                    private_message_object.recipient, 'out')
    if not bpio._dir_exist(local_msg_folder):
        bpio._dirs_make(local_msg_folder)
    local_msg_filename = os.path.join(local_msg_folder, message_id)
    if not bpio.WriteBinaryFile(local_msg_filename, serialized_message):
        lg.warn('failed writing outgoing message locally')
        return False
    remote_path_for_message = os.path.join('.messages', 'out',
                                           private_message_object.recipient,
                                           message_id)
    global_message_path = global_id.MakeGlobalID(customer=messages_key_id(),
                                                 path=remote_path_for_message)
    res = api.file_create(global_message_path)
    if res['status'] != 'OK':
        lg.warn('failed to create path "%s" in the catalog: %s' %
                (global_message_path, res['errors']))
        return False
    res = api.file_upload_start(local_msg_filename,
                                global_message_path,
                                wait_result=False)
    if res['status'] != 'OK':
        lg.warn('failed to upload message "%s": %s' %
                (global_message_path, res['errors']))
        return False
    return True
コード例 #24
0
def process(newpacket, info):
    from p2p import p2p_service
    from userid import my_id
    if not driver.is_on('service_p2p_hookups'):
        if _Debug:
            lg.out(
                _DebugLevel,
                'packet_in.process SKIP incoming packet, service_p2p_hookups is not started'
            )
        return None
    if _Debug:
        lg.out(
            _DebugLevel,
            'packet_in.process [%s/%s/%s]:%s(%s) from %s://%s is "%s"' % (
                nameurl.GetName(newpacket.OwnerID),
                nameurl.GetName(newpacket.CreatorID),
                nameurl.GetName(newpacket.RemoteID),
                newpacket.Command,
                newpacket.PacketID,
                info.proto,
                info.host,
                info.status,
            ))
    if info.status != 'finished':
        if _Debug:
            lg.out(_DebugLevel,
                   '    skip, packet status is : [%s]' % info.status)
        return None
    if newpacket.Command == commands.Identity():
        if newpacket.RemoteID != my_id.getLocalIDURL():
            if _Debug:
                lg.out(_DebugLevel,
                       '    incoming Identity is routed to another user')
            if not p2p_service.Identity(newpacket, send_ack=False):
                lg.warn('non-valid identity received')
                return None
            # remote peer sending a valid identity to another peer routed via my machine
            # need to handle that packet - it should be processed by proxy_server
            return handle(newpacket, info)
        # contact sending us current identity we might not have
        # so we handle it before check that packet is valid
        # because we might not have his identity on hands and so can not verify the packet
        # so we check that his Identity is valid and save it into cache
        # than we check the packet to be valid too.
        if not p2p_service.Identity(newpacket):
            lg.warn('non-valid identity received')
            return None
    if not identitycache.HasKey(newpacket.CreatorID):
        if _Debug:
            lg.out(
                _DebugLevel,
                '    will cache remote identity %s before processing incoming packet %s'
                % (newpacket.CreatorID, newpacket))
        d = identitycache.immediatelyCaching(newpacket.CreatorID)
        d.addCallback(lambda _: handle(newpacket, info))
        d.addErrback(lambda err: lg.err('failed caching remote %s identity: %s'
                                        % (newpacket.CreatorID, str(err))))
        return d
    return handle(newpacket, info)
コード例 #25
0
 def doRestartCustomersRejector(self, *args, **kwargs):
     """
     Action method.
     """
     if driver.is_on('service_customer_patrol'):
         # TODO: move this into a callback inside service_customer_patrol
         from supplier import customers_rejector
         customers_rejector.A('restart')
コード例 #26
0
def _list_active_connections(params):
    result = []
    if not driver.is_on('service_gateway'):
        return {'result': result, }
    from transport import gateway
    result = []
    wanted_protos = params.get('protos', [])
    if not wanted_protos:
        wanted_protos = gateway.list_active_transports()
    for proto in wanted_protos:
        for connection in gateway.list_active_sessions(proto):
            item = {
                'status': 'unknown',
                'state': 'unknown',
                'proto': proto,
                'host': 'unknown',
                'idurl': 'unknown',
                'bytes_sent': 0,
                'bytes_received': 0,
            }
            if proto == 'tcp':
                if hasattr(connection, 'stream'):
                    try:
                        host = '%s:%s' % (connection.peer_address[0], connection.peer_address[1])
                    except:
                        host = 'unknown'
                    item.update({
                        'status': 'active',
                        'state': connection.state,
                        'host': host,
                        'idurl': connection.peer_idurl or '',
                        'bytes_sent': connection.total_bytes_sent,
                        'bytes_received': connection.total_bytes_received,
                    })
                else:
                    try:
                        host = '%s:%s' % (connection.connection_address[0], connection.connection_address[1])
                    except:
                        host = 'unknown'
                    item.update({
                        'status': 'connecting',
                        'host': host,
                    })
            elif proto == 'udp':
                try:
                    host = '%s:%s' % (connection.peer_address[0], connection.peer_address[1])
                except:
                    host = 'unknown'
                item.update({
                    'status': 'active',
                    'state': connection.state,
                    'host': host,
                    'idurl': connection.peer_idurl or '',
                    'bytes_sent': connection.bytes_sent,
                    'bytes_received': connection.bytes_received,
                })
            result.append(item)
    return {'result': result, }
コード例 #27
0
ファイル: contactsdb.py プロジェクト: vesellov/bitdust.public
def contacts(include_all=False, include_enabled=True):
    """
    Return a union of suppliers and customers ID's.
    """
    result = set()
    if include_all or (include_enabled and driver.is_enabled('service_customer')) or driver.is_on('service_customer'):
        result.update(set(all_suppliers()))
    if include_all or (include_enabled and driver.is_enabled('service_supplier')) or driver.is_on('service_supplier'):
        result.update(set(customers() + known_customers()))
    if include_all or (include_enabled and driver.is_enabled('service_private_messages')) or driver.is_on('service_private_messages'):
        result.update(set(correspondents_ids()))
    if include_all or include_enabled:
        if driver.is_enabled('service_message_broker') or driver.is_on('service_message_broker'):
            from stream import message_peddler
            result.update(set(message_peddler.list_customers()))
            result.update(set(message_peddler.list_consumers_producers(include_consumers=True, include_producers=True)))
            result.update(set(message_peddler.list_known_brokers()))
    return list(result)
コード例 #28
0
ファイル: p2p_connector.py プロジェクト: StasEvseev/devel
 def doPropagateMyIdentity(self, *args, **kwargs):
     # TODO: need to run this actions one by one, not in parallel - use Defered chain
     if driver.is_on('service_entangled_dht'):
         from dht import dht_service
         dht_service.set_node_data('idurl', my_id.getLocalID())
     propagate.update()
     d = propagate.start(wide=True)
     d.addCallback(lambda contacts_list: self.automat(
         'my-id-propagated', contacts_list))
コード例 #29
0
def DeleteFile(request):
    """
    Delete one ore multiple files (that belongs to another user) or folders on my machine.
    """
    if _Debug:
        lg.out(
            _DebugLevel, 'p2p_service.DeleteFile [%s] by %s | %s' %
            (request.PacketID, request.OwnerID, request.CreatorID))
    if not driver.is_on('service_supplier'):
        return SendFail(request, 'supplier service is off')
    if request.Payload == '':
        ids = [request.PacketID]
    else:
        ids = request.Payload.split('\n')
    filescount = 0
    dirscount = 0
    for pcktID in ids:
        glob_path = global_id.ParseGlobalID(pcktID)
        if not glob_path['path']:
            # backward compatible check
            glob_path = global_id.ParseGlobalID(my_id.getGlobalID() + ':' +
                                                request.PacketID)
        if not glob_path['path']:
            lg.warn("got incorrect PacketID")
            SendFail(request, 'incorrect PacketID')
            return
        # TODO: add validation of customerGlobID
        # TODO: process requests from another customer
        filename = makeFilename(request.OwnerID, glob_path['path'])
        if filename == "":
            filename = constructFilename(request.OwnerID, glob_path['path'])
            if not os.path.exists(filename):
                lg.warn(
                    "had unknown customer: %s or pathID is not correct or not exist: %s"
                    % (nameurl.GetName(request.OwnerID), glob_path['path']))
                return SendFail(request, 'not a customer, or file not found')
        if os.path.isfile(filename):
            try:
                os.remove(filename)
                filescount += 1
            except:
                lg.exc()
        elif os.path.isdir(filename):
            try:
                bpio._dir_remove(filename)
                dirscount += 1
            except:
                lg.exc()
        else:
            lg.warn("path not found %s" % filename)
    if _Debug:
        lg.out(
            _DebugLevel,
            "p2p_service.DeleteFile from [%s] with %d IDs, %d files and %d folders were removed"
            % (nameurl.GetName(
                request.OwnerID), len(ids), filescount, dirscount))
    SendAck(request)
コード例 #30
0
ファイル: initializer.py プロジェクト: codingcosmonaut/devel
    def _on_tray_icon_command(self, cmd):
        if _Debug:
            lg.out(_DebugLevel,
                   "initializer._on_tray_icon_command : [%s]" % cmd)
        try:
            from main import shutdowner
            if cmd == 'exit':
                shutdowner.A('stop', 'exit')

            elif cmd == 'restart':
                shutdowner.A('stop', 'restart')

            elif cmd == 'reconnect':
                from p2p import network_connector
                if driver.is_on('service_network'):
                    network_connector.A('reconnect')

            elif cmd == 'show':
                # TODO: raise up electron window ?
                pass

            elif cmd == 'sync':
                try:
                    from updates import git_proc
                    from system import tray_icon

                    def _sync_callback(result):
                        if result == 'error':
                            tray_icon.draw_icon('error')
                            reactor.callLater(
                                5,
                                tray_icon.restore_icon)  # @UndefinedVariable
                            return
                        elif result == 'source-code-fetched':
                            tray_icon.draw_icon('updated')
                            reactor.callLater(
                                5,
                                tray_icon.restore_icon)  # @UndefinedVariable
                            return
                        tray_icon.restore_icon()

                    tray_icon.draw_icon('sync')
                    git_proc.sync(_sync_callback, update_method='reset')
                except:
                    lg.exc()

            elif cmd == 'hide':
                pass

            elif cmd == 'toolbar':
                pass

            else:
                lg.warn('wrong command: ' + str(cmd))
        except:
            lg.exc()