repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.remove_bundle_listener
def remove_bundle_listener(self, listener): """ Unregisters a bundle listener :param listener: The bundle listener to unregister :return: True if the listener has been unregistered, else False """ with self.__bnd_lock: if listener not in self.__bnd_listeners: return False self.__bnd_listeners.remove(listener) return True
python
def remove_bundle_listener(self, listener): """ Unregisters a bundle listener :param listener: The bundle listener to unregister :return: True if the listener has been unregistered, else False """ with self.__bnd_lock: if listener not in self.__bnd_listeners: return False self.__bnd_listeners.remove(listener) return True
Unregisters a bundle listener :param listener: The bundle listener to unregister :return: True if the listener has been unregistered, else False
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L757-L769
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.remove_framework_listener
def remove_framework_listener(self, listener): """ Unregisters a framework stop listener :param listener: The framework listener to unregister :return: True if the listener has been unregistered, else False """ with self.__fw_lock: try: self.__fw_listeners.remove(listener) return True except ValueError: return False
python
def remove_framework_listener(self, listener): """ Unregisters a framework stop listener :param listener: The framework listener to unregister :return: True if the listener has been unregistered, else False """ with self.__fw_lock: try: self.__fw_listeners.remove(listener) return True except ValueError: return False
Unregisters a framework stop listener :param listener: The framework listener to unregister :return: True if the listener has been unregistered, else False
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L771-L783
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.remove_service_listener
def remove_service_listener(self, listener): """ Unregisters a service listener :param listener: The service listener :return: True if the listener has been unregistered """ with self.__svc_lock: try: data = self.__listeners_data.pop(listener) spec_listeners = self.__svc_listeners[data.specification] spec_listeners.remove(data) if not spec_listeners: del self.__svc_listeners[data.specification] return True except KeyError: return False
python
def remove_service_listener(self, listener): """ Unregisters a service listener :param listener: The service listener :return: True if the listener has been unregistered """ with self.__svc_lock: try: data = self.__listeners_data.pop(listener) spec_listeners = self.__svc_listeners[data.specification] spec_listeners.remove(data) if not spec_listeners: del self.__svc_listeners[data.specification] return True except KeyError: return False
Unregisters a service listener :param listener: The service listener :return: True if the listener has been unregistered
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L785-L801
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.fire_bundle_event
def fire_bundle_event(self, event): """ Notifies bundle events listeners of a new event in the calling thread. :param event: The bundle event """ with self.__bnd_lock: # Copy the list of listeners listeners = self.__bnd_listeners[:] # Call'em all for listener in listeners: try: listener.bundle_changed(event) except: self._logger.exception("Error calling a bundle listener")
python
def fire_bundle_event(self, event): """ Notifies bundle events listeners of a new event in the calling thread. :param event: The bundle event """ with self.__bnd_lock: # Copy the list of listeners listeners = self.__bnd_listeners[:] # Call'em all for listener in listeners: try: listener.bundle_changed(event) except: self._logger.exception("Error calling a bundle listener")
Notifies bundle events listeners of a new event in the calling thread. :param event: The bundle event
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L803-L818
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.fire_framework_stopping
def fire_framework_stopping(self): """ Calls all framework listeners, telling them that the framework is stopping """ with self.__fw_lock: # Copy the list of listeners listeners = self.__fw_listeners[:] for listener in listeners: try: listener.framework_stopping() except: self._logger.exception( "An error occurred calling one of the " "framework stop listeners" )
python
def fire_framework_stopping(self): """ Calls all framework listeners, telling them that the framework is stopping """ with self.__fw_lock: # Copy the list of listeners listeners = self.__fw_listeners[:] for listener in listeners: try: listener.framework_stopping() except: self._logger.exception( "An error occurred calling one of the " "framework stop listeners" )
Calls all framework listeners, telling them that the framework is stopping
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L820-L836
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.fire_service_event
def fire_service_event(self, event): """ Notifies service events listeners of a new event in the calling thread. :param event: The service event """ # Get the service properties properties = event.get_service_reference().get_properties() svc_specs = properties[OBJECTCLASS] previous = None endmatch_event = None svc_modified = event.get_kind() == ServiceEvent.MODIFIED if svc_modified: # Modified service event : prepare the end match event previous = event.get_previous_properties() endmatch_event = ServiceEvent( ServiceEvent.MODIFIED_ENDMATCH, event.get_service_reference(), previous, ) with self.__svc_lock: # Get the listeners for this specification listeners = set() for spec in svc_specs: try: listeners.update(self.__svc_listeners[spec]) except KeyError: pass # Add those which listen to any specification try: listeners.update(self.__svc_listeners[None]) except KeyError: pass # Filter listeners with EventListenerHooks listeners = self._filter_with_hooks(event, listeners) # Get the listeners for this specification for data in listeners: # Default event to send : the one we received sent_event = event # Test if the service properties matches the filter ldap_filter = data.ldap_filter if ldap_filter is not None and not ldap_filter.matches(properties): # Event doesn't match listener filter... if ( svc_modified and previous is not None and ldap_filter.matches(previous) ): # ... but previous properties did match sent_event = endmatch_event else: # Didn't match before either, ignore it continue # Call'em try: data.listener.service_changed(sent_event) except: self._logger.exception("Error calling a service listener")
python
def fire_service_event(self, event): """ Notifies service events listeners of a new event in the calling thread. :param event: The service event """ # Get the service properties properties = event.get_service_reference().get_properties() svc_specs = properties[OBJECTCLASS] previous = None endmatch_event = None svc_modified = event.get_kind() == ServiceEvent.MODIFIED if svc_modified: # Modified service event : prepare the end match event previous = event.get_previous_properties() endmatch_event = ServiceEvent( ServiceEvent.MODIFIED_ENDMATCH, event.get_service_reference(), previous, ) with self.__svc_lock: # Get the listeners for this specification listeners = set() for spec in svc_specs: try: listeners.update(self.__svc_listeners[spec]) except KeyError: pass # Add those which listen to any specification try: listeners.update(self.__svc_listeners[None]) except KeyError: pass # Filter listeners with EventListenerHooks listeners = self._filter_with_hooks(event, listeners) # Get the listeners for this specification for data in listeners: # Default event to send : the one we received sent_event = event # Test if the service properties matches the filter ldap_filter = data.ldap_filter if ldap_filter is not None and not ldap_filter.matches(properties): # Event doesn't match listener filter... if ( svc_modified and previous is not None and ldap_filter.matches(previous) ): # ... but previous properties did match sent_event = endmatch_event else: # Didn't match before either, ignore it continue # Call'em try: data.listener.service_changed(sent_event) except: self._logger.exception("Error calling a service listener")
Notifies service events listeners of a new event in the calling thread. :param event: The service event
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L838-L902
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher._filter_with_hooks
def _filter_with_hooks(self, svc_event, listeners): """ Filters listeners with EventListenerHooks :param svc_event: ServiceEvent being triggered :param listeners: Listeners to filter :return: A list of listeners with hook references """ svc_ref = svc_event.get_service_reference() # Get EventListenerHooks service refs from registry hook_refs = self._registry.find_service_references( SERVICE_EVENT_LISTENER_HOOK ) # only do something if there are some hook_refs if hook_refs: # Associate bundle context to hooks ctx_listeners = {} for listener in listeners: context = listener.bundle_context ctx_listeners.setdefault(context, []).append(listener) # Convert the dictionary to a shrinkable one, # with shrinkable lists of listeners shrinkable_ctx_listeners = ShrinkableMap( { context: ShrinkableList(value) for context, value in ctx_listeners.items() } ) for hook_ref in hook_refs: if not svc_ref == hook_ref: # Get the bundle of the hook service hook_bundle = hook_ref.get_bundle() # lookup service from registry hook_svc = self._registry.get_service(hook_bundle, hook_ref) if hook_svc is not None: # call event method of the hook service, # pass in svc_event and shrinkable_ctx_listeners # (which can be modified by hook) try: hook_svc.event(svc_event, shrinkable_ctx_listeners) except: self._logger.exception( "Error calling EventListenerHook" ) finally: # Clean up the service self._registry.unget_service(hook_bundle, hook_ref) # Convert the shrinkable_ctx_listeners back to a list of listeners # before returning ret_listeners = set() for bnd_listeners in shrinkable_ctx_listeners.values(): ret_listeners.update(bnd_listeners) return ret_listeners # No hook ref return listeners
python
def _filter_with_hooks(self, svc_event, listeners): """ Filters listeners with EventListenerHooks :param svc_event: ServiceEvent being triggered :param listeners: Listeners to filter :return: A list of listeners with hook references """ svc_ref = svc_event.get_service_reference() # Get EventListenerHooks service refs from registry hook_refs = self._registry.find_service_references( SERVICE_EVENT_LISTENER_HOOK ) # only do something if there are some hook_refs if hook_refs: # Associate bundle context to hooks ctx_listeners = {} for listener in listeners: context = listener.bundle_context ctx_listeners.setdefault(context, []).append(listener) # Convert the dictionary to a shrinkable one, # with shrinkable lists of listeners shrinkable_ctx_listeners = ShrinkableMap( { context: ShrinkableList(value) for context, value in ctx_listeners.items() } ) for hook_ref in hook_refs: if not svc_ref == hook_ref: # Get the bundle of the hook service hook_bundle = hook_ref.get_bundle() # lookup service from registry hook_svc = self._registry.get_service(hook_bundle, hook_ref) if hook_svc is not None: # call event method of the hook service, # pass in svc_event and shrinkable_ctx_listeners # (which can be modified by hook) try: hook_svc.event(svc_event, shrinkable_ctx_listeners) except: self._logger.exception( "Error calling EventListenerHook" ) finally: # Clean up the service self._registry.unget_service(hook_bundle, hook_ref) # Convert the shrinkable_ctx_listeners back to a list of listeners # before returning ret_listeners = set() for bnd_listeners in shrinkable_ctx_listeners.values(): ret_listeners.update(bnd_listeners) return ret_listeners # No hook ref return listeners
Filters listeners with EventListenerHooks :param svc_event: ServiceEvent being triggered :param listeners: Listeners to filter :return: A list of listeners with hook references
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L904-L963
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.clear
def clear(self): """ Clears the registry """ with self.__svc_lock: self.__svc_registry.clear() self.__svc_factories.clear() self.__svc_specs.clear() self.__bundle_svc.clear() self.__bundle_imports.clear() self.__factory_usage.clear() self.__pending_services.clear()
python
def clear(self): """ Clears the registry """ with self.__svc_lock: self.__svc_registry.clear() self.__svc_factories.clear() self.__svc_specs.clear() self.__bundle_svc.clear() self.__bundle_imports.clear() self.__factory_usage.clear() self.__pending_services.clear()
Clears the registry
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1016-L1027
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.register
def register( self, bundle, classes, properties, svc_instance, factory, prototype ): """ Registers a service. :param bundle: The bundle that registers the service :param classes: The classes implemented by the service :param properties: The properties associated to the service :param svc_instance: The instance of the service :param factory: If True, the given service is a service factory :param prototype: If True, the given service is a prototype service factory (the factory argument is considered True) :return: The ServiceRegistration object """ with self.__svc_lock: # Prepare properties service_id = self.__next_service_id self.__next_service_id += 1 properties[OBJECTCLASS] = classes properties[SERVICE_ID] = service_id properties[SERVICE_BUNDLEID] = bundle.get_bundle_id() # Compute service scope if prototype: properties[SERVICE_SCOPE] = SCOPE_PROTOTYPE elif factory: properties[SERVICE_SCOPE] = SCOPE_BUNDLE else: properties[SERVICE_SCOPE] = SCOPE_SINGLETON # Force to have a valid service ranking try: properties[SERVICE_RANKING] = int(properties[SERVICE_RANKING]) except (KeyError, ValueError, TypeError): properties[SERVICE_RANKING] = 0 # Make the service reference svc_ref = ServiceReference(bundle, properties) # Make the service registration svc_registration = ServiceRegistration( self.__framework, svc_ref, properties, self.__sort_registry ) # Store service information if prototype or factory: self.__svc_factories[svc_ref] = (svc_instance, svc_registration) # Also store factories, as they must appear like any other service self.__svc_registry[svc_ref] = svc_instance for spec in classes: spec_refs = self.__svc_specs.setdefault(spec, []) bisect.insort_left(spec_refs, svc_ref) # Reverse map, to ease bundle/service association bundle_services = self.__bundle_svc.setdefault(bundle, set()) bundle_services.add(svc_ref) return svc_registration
python
def register( self, bundle, classes, properties, svc_instance, factory, prototype ): """ Registers a service. :param bundle: The bundle that registers the service :param classes: The classes implemented by the service :param properties: The properties associated to the service :param svc_instance: The instance of the service :param factory: If True, the given service is a service factory :param prototype: If True, the given service is a prototype service factory (the factory argument is considered True) :return: The ServiceRegistration object """ with self.__svc_lock: # Prepare properties service_id = self.__next_service_id self.__next_service_id += 1 properties[OBJECTCLASS] = classes properties[SERVICE_ID] = service_id properties[SERVICE_BUNDLEID] = bundle.get_bundle_id() # Compute service scope if prototype: properties[SERVICE_SCOPE] = SCOPE_PROTOTYPE elif factory: properties[SERVICE_SCOPE] = SCOPE_BUNDLE else: properties[SERVICE_SCOPE] = SCOPE_SINGLETON # Force to have a valid service ranking try: properties[SERVICE_RANKING] = int(properties[SERVICE_RANKING]) except (KeyError, ValueError, TypeError): properties[SERVICE_RANKING] = 0 # Make the service reference svc_ref = ServiceReference(bundle, properties) # Make the service registration svc_registration = ServiceRegistration( self.__framework, svc_ref, properties, self.__sort_registry ) # Store service information if prototype or factory: self.__svc_factories[svc_ref] = (svc_instance, svc_registration) # Also store factories, as they must appear like any other service self.__svc_registry[svc_ref] = svc_instance for spec in classes: spec_refs = self.__svc_specs.setdefault(spec, []) bisect.insort_left(spec_refs, svc_ref) # Reverse map, to ease bundle/service association bundle_services = self.__bundle_svc.setdefault(bundle, set()) bundle_services.add(svc_ref) return svc_registration
Registers a service. :param bundle: The bundle that registers the service :param classes: The classes implemented by the service :param properties: The properties associated to the service :param svc_instance: The instance of the service :param factory: If True, the given service is a service factory :param prototype: If True, the given service is a prototype service factory (the factory argument is considered True) :return: The ServiceRegistration object
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1029-L1088
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.__sort_registry
def __sort_registry(self, svc_ref): # type: (ServiceReference) -> None """ Sorts the registry, after the update of the sort key of given service reference :param svc_ref: A service reference with a modified sort key """ with self.__svc_lock: if svc_ref not in self.__svc_registry: raise BundleException("Unknown service: {0}".format(svc_ref)) # Remove current references for spec in svc_ref.get_property(OBJECTCLASS): # Use bisect to remove the reference (faster) spec_refs = self.__svc_specs[spec] idx = bisect.bisect_left(spec_refs, svc_ref) del spec_refs[idx] # ... use the new sort key svc_ref.update_sort_key() for spec in svc_ref.get_property(OBJECTCLASS): # ... and insert it again spec_refs = self.__svc_specs[spec] bisect.insort_left(spec_refs, svc_ref)
python
def __sort_registry(self, svc_ref): # type: (ServiceReference) -> None """ Sorts the registry, after the update of the sort key of given service reference :param svc_ref: A service reference with a modified sort key """ with self.__svc_lock: if svc_ref not in self.__svc_registry: raise BundleException("Unknown service: {0}".format(svc_ref)) # Remove current references for spec in svc_ref.get_property(OBJECTCLASS): # Use bisect to remove the reference (faster) spec_refs = self.__svc_specs[spec] idx = bisect.bisect_left(spec_refs, svc_ref) del spec_refs[idx] # ... use the new sort key svc_ref.update_sort_key() for spec in svc_ref.get_property(OBJECTCLASS): # ... and insert it again spec_refs = self.__svc_specs[spec] bisect.insort_left(spec_refs, svc_ref)
Sorts the registry, after the update of the sort key of given service reference :param svc_ref: A service reference with a modified sort key
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1090-L1115
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.unregister
def unregister(self, svc_ref): # type: (ServiceReference) -> Any """ Unregisters a service :param svc_ref: A service reference :return: The unregistered service instance :raise BundleException: Unknown service reference """ with self.__svc_lock: try: # Try in pending services return self.__pending_services.pop(svc_ref) except KeyError: # Not pending: continue pass if svc_ref not in self.__svc_registry: raise BundleException("Unknown service: {0}".format(svc_ref)) # Get the owner bundle = svc_ref.get_bundle() # Get the service instance service = self.__svc_registry.pop(svc_ref) for spec in svc_ref.get_property(OBJECTCLASS): spec_services = self.__svc_specs[spec] # Use bisect to remove the reference (faster) idx = bisect.bisect_left(spec_services, svc_ref) del spec_services[idx] if not spec_services: del self.__svc_specs[spec] # Remove the service factory if svc_ref.is_factory(): # Call unget_service for all client bundle factory, svc_reg = self.__svc_factories.pop(svc_ref) for counter in self.__factory_usage.values(): counter.cleanup_service(factory, svc_reg) else: # Delete bundle association bundle_services = self.__bundle_svc[bundle] bundle_services.remove(svc_ref) if not bundle_services: # Don't keep empty lists del self.__bundle_svc[bundle] return service
python
def unregister(self, svc_ref): # type: (ServiceReference) -> Any """ Unregisters a service :param svc_ref: A service reference :return: The unregistered service instance :raise BundleException: Unknown service reference """ with self.__svc_lock: try: # Try in pending services return self.__pending_services.pop(svc_ref) except KeyError: # Not pending: continue pass if svc_ref not in self.__svc_registry: raise BundleException("Unknown service: {0}".format(svc_ref)) # Get the owner bundle = svc_ref.get_bundle() # Get the service instance service = self.__svc_registry.pop(svc_ref) for spec in svc_ref.get_property(OBJECTCLASS): spec_services = self.__svc_specs[spec] # Use bisect to remove the reference (faster) idx = bisect.bisect_left(spec_services, svc_ref) del spec_services[idx] if not spec_services: del self.__svc_specs[spec] # Remove the service factory if svc_ref.is_factory(): # Call unget_service for all client bundle factory, svc_reg = self.__svc_factories.pop(svc_ref) for counter in self.__factory_usage.values(): counter.cleanup_service(factory, svc_reg) else: # Delete bundle association bundle_services = self.__bundle_svc[bundle] bundle_services.remove(svc_ref) if not bundle_services: # Don't keep empty lists del self.__bundle_svc[bundle] return service
Unregisters a service :param svc_ref: A service reference :return: The unregistered service instance :raise BundleException: Unknown service reference
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1117-L1165
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.hide_bundle_services
def hide_bundle_services(self, bundle): """ Hides the services of the given bundle (removes them from lists, but lets them be unregistered) :param bundle: The bundle providing services :return: The references of the hidden services """ with self.__svc_lock: try: svc_refs = self.__bundle_svc.pop(bundle) except KeyError: # Nothing to do return set() else: # Clean the registry specs = set() for svc_ref in svc_refs: if svc_ref.is_factory(): continue # Remove direct references self.__pending_services[svc_ref] = self.__svc_registry.pop( svc_ref ) specs.update(svc_ref.get_property(OBJECTCLASS)) # Clean the specifications cache for spec in svc_ref.get_property(OBJECTCLASS): spec_services = self.__svc_specs[spec] # Use bisect to remove the reference (faster) idx = bisect.bisect_left(spec_services, svc_ref) del spec_services[idx] if not spec_services: del self.__svc_specs[spec] return svc_refs
python
def hide_bundle_services(self, bundle): """ Hides the services of the given bundle (removes them from lists, but lets them be unregistered) :param bundle: The bundle providing services :return: The references of the hidden services """ with self.__svc_lock: try: svc_refs = self.__bundle_svc.pop(bundle) except KeyError: # Nothing to do return set() else: # Clean the registry specs = set() for svc_ref in svc_refs: if svc_ref.is_factory(): continue # Remove direct references self.__pending_services[svc_ref] = self.__svc_registry.pop( svc_ref ) specs.update(svc_ref.get_property(OBJECTCLASS)) # Clean the specifications cache for spec in svc_ref.get_property(OBJECTCLASS): spec_services = self.__svc_specs[spec] # Use bisect to remove the reference (faster) idx = bisect.bisect_left(spec_services, svc_ref) del spec_services[idx] if not spec_services: del self.__svc_specs[spec] return svc_refs
Hides the services of the given bundle (removes them from lists, but lets them be unregistered) :param bundle: The bundle providing services :return: The references of the hidden services
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1167-L1203
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.find_service_references
def find_service_references( self, clazz=None, ldap_filter=None, only_one=False ): """ Finds all services references matching the given filter. :param clazz: Class implemented by the service :param ldap_filter: Service filter :param only_one: Return the first matching service reference only :return: A list of found references, or None :raise BundleException: An error occurred looking for service references """ with self.__svc_lock: if clazz is None and ldap_filter is None: # Return a sorted copy of the keys list # Do not return None, as the whole content was required return sorted(self.__svc_registry.keys()) if hasattr(clazz, "__name__"): # Escape the type name clazz = ldapfilter.escape_LDAP(clazz.__name__) elif is_string(clazz): # Escape the class name clazz = ldapfilter.escape_LDAP(clazz) if clazz is None: # Directly use the given filter refs_set = sorted(self.__svc_registry.keys()) else: try: # Only for references with the given specification refs_set = iter(self.__svc_specs[clazz]) except KeyError: # No matching specification return None # Parse the filter try: new_filter = ldapfilter.get_ldap_filter(ldap_filter) except ValueError as ex: raise BundleException(ex) if new_filter is not None: # Prepare a generator, as we might not need a complete # walk-through refs_set = ( ref for ref in refs_set if new_filter.matches(ref.get_properties()) ) if only_one: # Return the first element in the list/generator try: return [next(refs_set)] except StopIteration: # No match return None # Get all the matching references return list(refs_set) or None
python
def find_service_references( self, clazz=None, ldap_filter=None, only_one=False ): """ Finds all services references matching the given filter. :param clazz: Class implemented by the service :param ldap_filter: Service filter :param only_one: Return the first matching service reference only :return: A list of found references, or None :raise BundleException: An error occurred looking for service references """ with self.__svc_lock: if clazz is None and ldap_filter is None: # Return a sorted copy of the keys list # Do not return None, as the whole content was required return sorted(self.__svc_registry.keys()) if hasattr(clazz, "__name__"): # Escape the type name clazz = ldapfilter.escape_LDAP(clazz.__name__) elif is_string(clazz): # Escape the class name clazz = ldapfilter.escape_LDAP(clazz) if clazz is None: # Directly use the given filter refs_set = sorted(self.__svc_registry.keys()) else: try: # Only for references with the given specification refs_set = iter(self.__svc_specs[clazz]) except KeyError: # No matching specification return None # Parse the filter try: new_filter = ldapfilter.get_ldap_filter(ldap_filter) except ValueError as ex: raise BundleException(ex) if new_filter is not None: # Prepare a generator, as we might not need a complete # walk-through refs_set = ( ref for ref in refs_set if new_filter.matches(ref.get_properties()) ) if only_one: # Return the first element in the list/generator try: return [next(refs_set)] except StopIteration: # No match return None # Get all the matching references return list(refs_set) or None
Finds all services references matching the given filter. :param clazz: Class implemented by the service :param ldap_filter: Service filter :param only_one: Return the first matching service reference only :return: A list of found references, or None :raise BundleException: An error occurred looking for service references
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1205-L1266
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.get_bundle_imported_services
def get_bundle_imported_services(self, bundle): """ Returns this bundle's ServiceReference list for all services it is using or returns None if this bundle is not using any services. A bundle is considered to be using a service if its use count for that service is greater than zero. The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :param bundle: The bundle to look into :return: The references of the services used by this bundle """ with self.__svc_lock: return sorted(self.__bundle_imports.get(bundle, []))
python
def get_bundle_imported_services(self, bundle): """ Returns this bundle's ServiceReference list for all services it is using or returns None if this bundle is not using any services. A bundle is considered to be using a service if its use count for that service is greater than zero. The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :param bundle: The bundle to look into :return: The references of the services used by this bundle """ with self.__svc_lock: return sorted(self.__bundle_imports.get(bundle, []))
Returns this bundle's ServiceReference list for all services it is using or returns None if this bundle is not using any services. A bundle is considered to be using a service if its use count for that service is greater than zero. The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :param bundle: The bundle to look into :return: The references of the services used by this bundle
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1268-L1283
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.get_bundle_registered_services
def get_bundle_registered_services(self, bundle): # type: (Any) -> List[ServiceReference] """ Retrieves the services registered by the given bundle. Returns None if the bundle didn't register any service. :param bundle: The bundle to look into :return: The references to the services registered by the bundle """ with self.__svc_lock: return sorted(self.__bundle_svc.get(bundle, []))
python
def get_bundle_registered_services(self, bundle): # type: (Any) -> List[ServiceReference] """ Retrieves the services registered by the given bundle. Returns None if the bundle didn't register any service. :param bundle: The bundle to look into :return: The references to the services registered by the bundle """ with self.__svc_lock: return sorted(self.__bundle_svc.get(bundle, []))
Retrieves the services registered by the given bundle. Returns None if the bundle didn't register any service. :param bundle: The bundle to look into :return: The references to the services registered by the bundle
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1285-L1295
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.get_service
def get_service(self, bundle, reference): # type: (Any, ServiceReference) -> Any """ Retrieves the service corresponding to the given reference :param bundle: The bundle requiring the service :param reference: A service reference :return: The requested service :raise BundleException: The service could not be found """ with self.__svc_lock: if reference.is_factory(): return self.__get_service_from_factory(bundle, reference) # Be sure to have the instance try: service = self.__svc_registry[reference] # Indicate the dependency imports = self.__bundle_imports.setdefault(bundle, {}) imports.setdefault(reference, _UsageCounter()).inc() reference.used_by(bundle) return service except KeyError: # Not found raise BundleException( "Service not found (reference: {0})".format(reference) )
python
def get_service(self, bundle, reference): # type: (Any, ServiceReference) -> Any """ Retrieves the service corresponding to the given reference :param bundle: The bundle requiring the service :param reference: A service reference :return: The requested service :raise BundleException: The service could not be found """ with self.__svc_lock: if reference.is_factory(): return self.__get_service_from_factory(bundle, reference) # Be sure to have the instance try: service = self.__svc_registry[reference] # Indicate the dependency imports = self.__bundle_imports.setdefault(bundle, {}) imports.setdefault(reference, _UsageCounter()).inc() reference.used_by(bundle) return service except KeyError: # Not found raise BundleException( "Service not found (reference: {0})".format(reference) )
Retrieves the service corresponding to the given reference :param bundle: The bundle requiring the service :param reference: A service reference :return: The requested service :raise BundleException: The service could not be found
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1297-L1324
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.__get_service_from_factory
def __get_service_from_factory(self, bundle, reference): # type: (Any, ServiceReference) -> Any """ Returns a service instance from a service factory or a prototype service factory :param bundle: The bundle requiring the service :param reference: A reference pointing to a factory :return: The requested service :raise BundleException: The service could not be found """ try: factory, svc_reg = self.__svc_factories[reference] # Indicate the dependency imports = self.__bundle_imports.setdefault(bundle, {}) if reference not in imports: # New reference usage: store a single usage # The Factory counter will handle the rest usage_counter = _UsageCounter() usage_counter.inc() imports[reference] = usage_counter reference.used_by(bundle) # Check the per-bundle usage counter factory_counter = self.__factory_usage.setdefault( bundle, _FactoryCounter(bundle) ) return factory_counter.get_service(factory, svc_reg) except KeyError: # Not found raise BundleException( "Service not found (reference: {0})".format(reference) )
python
def __get_service_from_factory(self, bundle, reference): # type: (Any, ServiceReference) -> Any """ Returns a service instance from a service factory or a prototype service factory :param bundle: The bundle requiring the service :param reference: A reference pointing to a factory :return: The requested service :raise BundleException: The service could not be found """ try: factory, svc_reg = self.__svc_factories[reference] # Indicate the dependency imports = self.__bundle_imports.setdefault(bundle, {}) if reference not in imports: # New reference usage: store a single usage # The Factory counter will handle the rest usage_counter = _UsageCounter() usage_counter.inc() imports[reference] = usage_counter reference.used_by(bundle) # Check the per-bundle usage counter factory_counter = self.__factory_usage.setdefault( bundle, _FactoryCounter(bundle) ) return factory_counter.get_service(factory, svc_reg) except KeyError: # Not found raise BundleException( "Service not found (reference: {0})".format(reference) )
Returns a service instance from a service factory or a prototype service factory :param bundle: The bundle requiring the service :param reference: A reference pointing to a factory :return: The requested service :raise BundleException: The service could not be found
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1326-L1359
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.unget_used_services
def unget_used_services(self, bundle): """ Cleans up all service usages of the given bundle. :param bundle: Bundle to be cleaned up """ # Pop used references try: imported_refs = list(self.__bundle_imports.pop(bundle)) except KeyError: # Nothing to do return for svc_ref in imported_refs: # Remove usage marker svc_ref.unused_by(bundle) if svc_ref.is_prototype(): # Get factory information and clean up the service from the # factory counter factory_counter = self.__factory_usage.pop(bundle) factory, svc_reg = self.__svc_factories[svc_ref] factory_counter.cleanup_service(factory, svc_reg) elif svc_ref.is_factory(): # Factory service, release it the standard way self.__unget_service_from_factory(bundle, svc_ref) # Clean up local structures try: del self.__factory_usage[bundle] except KeyError: pass try: self.__bundle_imports.pop(bundle).clear() except KeyError: pass
python
def unget_used_services(self, bundle): """ Cleans up all service usages of the given bundle. :param bundle: Bundle to be cleaned up """ # Pop used references try: imported_refs = list(self.__bundle_imports.pop(bundle)) except KeyError: # Nothing to do return for svc_ref in imported_refs: # Remove usage marker svc_ref.unused_by(bundle) if svc_ref.is_prototype(): # Get factory information and clean up the service from the # factory counter factory_counter = self.__factory_usage.pop(bundle) factory, svc_reg = self.__svc_factories[svc_ref] factory_counter.cleanup_service(factory, svc_reg) elif svc_ref.is_factory(): # Factory service, release it the standard way self.__unget_service_from_factory(bundle, svc_ref) # Clean up local structures try: del self.__factory_usage[bundle] except KeyError: pass try: self.__bundle_imports.pop(bundle).clear() except KeyError: pass
Cleans up all service usages of the given bundle. :param bundle: Bundle to be cleaned up
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1361-L1397
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.unget_service
def unget_service(self, bundle, reference, service=None): # type: (Any, ServiceReference, Any) -> bool """ Removes the usage of a service by a bundle :param bundle: The bundle that used the service :param reference: A service reference :param service: Service instance (for Prototype Service Factories) :return: True if the bundle usage has been removed """ with self.__svc_lock: if reference.is_prototype(): return self.__unget_service_from_factory( bundle, reference, service ) elif reference.is_factory(): return self.__unget_service_from_factory(bundle, reference) try: # Remove the service reference from the bundle imports = self.__bundle_imports[bundle] if not imports[reference].dec(): # No more reference to it del imports[reference] except KeyError: # Unknown reference return False else: # Clean up if not imports: del self.__bundle_imports[bundle] # Update the service reference reference.unused_by(bundle) return True
python
def unget_service(self, bundle, reference, service=None): # type: (Any, ServiceReference, Any) -> bool """ Removes the usage of a service by a bundle :param bundle: The bundle that used the service :param reference: A service reference :param service: Service instance (for Prototype Service Factories) :return: True if the bundle usage has been removed """ with self.__svc_lock: if reference.is_prototype(): return self.__unget_service_from_factory( bundle, reference, service ) elif reference.is_factory(): return self.__unget_service_from_factory(bundle, reference) try: # Remove the service reference from the bundle imports = self.__bundle_imports[bundle] if not imports[reference].dec(): # No more reference to it del imports[reference] except KeyError: # Unknown reference return False else: # Clean up if not imports: del self.__bundle_imports[bundle] # Update the service reference reference.unused_by(bundle) return True
Removes the usage of a service by a bundle :param bundle: The bundle that used the service :param reference: A service reference :param service: Service instance (for Prototype Service Factories) :return: True if the bundle usage has been removed
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1399-L1433
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistry.__unget_service_from_factory
def __unget_service_from_factory(self, bundle, reference, service=None): # type: (Any, ServiceReference, Any) -> bool """ Removes the usage of a a service factory or a prototype service factory by a bundle :param bundle: The bundle that used the service :param reference: A service reference :param service: Service instance (for prototype factories) :return: True if the bundle usage has been removed """ try: factory, svc_reg = self.__svc_factories[reference] except KeyError: # Unknown service reference return False # Check the per-bundle usage counter try: counter = self.__factory_usage[bundle] except KeyError: # Unknown reference to a factory return False else: if counter.unget_service(factory, svc_reg, service): try: # No more dependency reference.unused_by(bundle) # All references have been taken away: clean up if not self.__factory_usage[bundle].is_used(): del self.__factory_usage[bundle] # Remove the service reference from the bundle imports = self.__bundle_imports[bundle] del imports[reference] except KeyError: # Unknown reference return False else: # Clean up if not imports: del self.__bundle_imports[bundle] return True
python
def __unget_service_from_factory(self, bundle, reference, service=None): # type: (Any, ServiceReference, Any) -> bool """ Removes the usage of a a service factory or a prototype service factory by a bundle :param bundle: The bundle that used the service :param reference: A service reference :param service: Service instance (for prototype factories) :return: True if the bundle usage has been removed """ try: factory, svc_reg = self.__svc_factories[reference] except KeyError: # Unknown service reference return False # Check the per-bundle usage counter try: counter = self.__factory_usage[bundle] except KeyError: # Unknown reference to a factory return False else: if counter.unget_service(factory, svc_reg, service): try: # No more dependency reference.unused_by(bundle) # All references have been taken away: clean up if not self.__factory_usage[bundle].is_used(): del self.__factory_usage[bundle] # Remove the service reference from the bundle imports = self.__bundle_imports[bundle] del imports[reference] except KeyError: # Unknown reference return False else: # Clean up if not imports: del self.__bundle_imports[bundle] return True
Removes the usage of a a service factory or a prototype service factory by a bundle :param bundle: The bundle that used the service :param reference: A service reference :param service: Service instance (for prototype factories) :return: True if the bundle usage has been removed
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1435-L1479
tcalmant/ipopo
pelix/remote/edef_io.py
EDEFReader._convert_value
def _convert_value(vtype, value): """ Converts the given value string according to the given type :param vtype: Type of the value :param value: String form of the value :return: The converted value :raise ValueError: Conversion failed """ # Normalize value value = value.strip() if vtype == TYPE_STRING: # Nothing to do return value elif vtype in TYPES_INT: return int(value) elif vtype in TYPES_FLOAT: return float(value) elif vtype in TYPES_BOOLEAN: # Compare lower-case value return value.lower() not in ("false", "0") elif vtype in TYPES_CHAR: return value[0] # No luck raise ValueError("Unknown value type: {0}".format(vtype))
python
def _convert_value(vtype, value): """ Converts the given value string according to the given type :param vtype: Type of the value :param value: String form of the value :return: The converted value :raise ValueError: Conversion failed """ # Normalize value value = value.strip() if vtype == TYPE_STRING: # Nothing to do return value elif vtype in TYPES_INT: return int(value) elif vtype in TYPES_FLOAT: return float(value) elif vtype in TYPES_BOOLEAN: # Compare lower-case value return value.lower() not in ("false", "0") elif vtype in TYPES_CHAR: return value[0] # No luck raise ValueError("Unknown value type: {0}".format(vtype))
Converts the given value string according to the given type :param vtype: Type of the value :param value: String form of the value :return: The converted value :raise ValueError: Conversion failed
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/edef_io.py#L122-L148
tcalmant/ipopo
pelix/remote/edef_io.py
EDEFWriter._indent
def _indent(self, element, level=0, prefix="\t"): """ In-place Element text auto-indent, for pretty printing. Code from: http://effbot.org/zone/element-lib.htm#prettyprint :param element: An Element object :param level: Level of indentation :param prefix: String to use for each indentation """ element_prefix = "\r\n{0}".format(level * prefix) if len(element): if not element.text or not element.text.strip(): element.text = element_prefix + prefix if not element.tail or not element.tail.strip(): element.tail = element_prefix # Yep, let the "element" variable be overwritten # pylint: disable=R1704 for element in element: self._indent(element, level + 1, prefix) # Tail of the last child if not element.tail or not element.tail.strip(): element.tail = element_prefix else: if level and (not element.tail or not element.tail.strip()): element.tail = element_prefix
python
def _indent(self, element, level=0, prefix="\t"): """ In-place Element text auto-indent, for pretty printing. Code from: http://effbot.org/zone/element-lib.htm#prettyprint :param element: An Element object :param level: Level of indentation :param prefix: String to use for each indentation """ element_prefix = "\r\n{0}".format(level * prefix) if len(element): if not element.text or not element.text.strip(): element.text = element_prefix + prefix if not element.tail or not element.tail.strip(): element.tail = element_prefix # Yep, let the "element" variable be overwritten # pylint: disable=R1704 for element in element: self._indent(element, level + 1, prefix) # Tail of the last child if not element.tail or not element.tail.strip(): element.tail = element_prefix else: if level and (not element.tail or not element.tail.strip()): element.tail = element_prefix
In-place Element text auto-indent, for pretty printing. Code from: http://effbot.org/zone/element-lib.htm#prettyprint :param element: An Element object :param level: Level of indentation :param prefix: String to use for each indentation
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/edef_io.py#L253-L283
tcalmant/ipopo
pelix/remote/edef_io.py
EDEFWriter._add_container
def _add_container(props_node, tag, container): """ Walks through the given container and fills the node :param props_node: A property node :param tag: Name of the container tag :param container: The container """ values_node = ElementTree.SubElement(props_node, tag) for value in container: value_node = ElementTree.SubElement(values_node, TAG_VALUE) value_node.text = str(value)
python
def _add_container(props_node, tag, container): """ Walks through the given container and fills the node :param props_node: A property node :param tag: Name of the container tag :param container: The container """ values_node = ElementTree.SubElement(props_node, tag) for value in container: value_node = ElementTree.SubElement(values_node, TAG_VALUE) value_node.text = str(value)
Walks through the given container and fills the node :param props_node: A property node :param tag: Name of the container tag :param container: The container
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/edef_io.py#L286-L297
tcalmant/ipopo
pelix/remote/edef_io.py
EDEFWriter._get_type
def _get_type(name, value): """ Returns the type associated to the given name or value :param name: Property name :param value: Property value :return: A value type name """ # Types forced for known keys if name in TYPED_BOOL: return TYPE_BOOLEAN elif name in TYPED_LONG: return TYPE_LONG elif name in TYPED_STRING: return TYPE_STRING # We need to analyze the content of value if isinstance(value, (tuple, list, set)): # Get the type from container content try: # Extract value value = next(iter(value)) except StopIteration: # Empty list, can't check return TYPE_STRING # Single value if isinstance(value, int): # Integer return TYPE_LONG elif isinstance(value, float): # Float return TYPE_DOUBLE elif isinstance(value, type(ElementTree.Element(None))): # XML return XML_VALUE # Default: String return TYPE_STRING
python
def _get_type(name, value): """ Returns the type associated to the given name or value :param name: Property name :param value: Property value :return: A value type name """ # Types forced for known keys if name in TYPED_BOOL: return TYPE_BOOLEAN elif name in TYPED_LONG: return TYPE_LONG elif name in TYPED_STRING: return TYPE_STRING # We need to analyze the content of value if isinstance(value, (tuple, list, set)): # Get the type from container content try: # Extract value value = next(iter(value)) except StopIteration: # Empty list, can't check return TYPE_STRING # Single value if isinstance(value, int): # Integer return TYPE_LONG elif isinstance(value, float): # Float return TYPE_DOUBLE elif isinstance(value, type(ElementTree.Element(None))): # XML return XML_VALUE # Default: String return TYPE_STRING
Returns the type associated to the given name or value :param name: Property name :param value: Property value :return: A value type name
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/edef_io.py#L300-L343
tcalmant/ipopo
pelix/remote/edef_io.py
EDEFWriter.to_string
def to_string(self, endpoints): """ Converts the given endpoint description beans into a string :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document """ # Make the ElementTree root = self._make_xml(endpoints) tree = ElementTree.ElementTree(root) # Force the default name space ElementTree.register_namespace("", EDEF_NAMESPACE) # Make the XML for encoding in "unicode", "UTF-8": # Prepare a StringIO output output = StringIO() try: # Try to write with a correct encoding tree.write( output, encoding=encoding, xml_declaration=True, method="xml", ) break except LookupError: # 'unicode' is needed in Python 3, but unknown in Python 2... continue else: raise LookupError("Couldn't find a valid encoding") return output.getvalue()
python
def to_string(self, endpoints): """ Converts the given endpoint description beans into a string :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document """ # Make the ElementTree root = self._make_xml(endpoints) tree = ElementTree.ElementTree(root) # Force the default name space ElementTree.register_namespace("", EDEF_NAMESPACE) # Make the XML for encoding in "unicode", "UTF-8": # Prepare a StringIO output output = StringIO() try: # Try to write with a correct encoding tree.write( output, encoding=encoding, xml_declaration=True, method="xml", ) break except LookupError: # 'unicode' is needed in Python 3, but unknown in Python 2... continue else: raise LookupError("Couldn't find a valid encoding") return output.getvalue()
Converts the given endpoint description beans into a string :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/edef_io.py#L413-L449
tcalmant/ipopo
pelix/misc/xmpp.py
BasicBot.connect
def connect( self, host, port=5222, reattempt=False, use_tls=True, use_ssl=False ): # pylint: disable=W0221 """ Connects to the server. By default, uses an un-encrypted connection, as it won't connect to an OpenFire server otherwise :param host: Server host name :param port: Server port (default: 5222) :param reattempt: If True, tries to connect to the server until it succeeds :param use_tls: Use STARTTLS :param use_ssl: Server connection is encrypted :return: True if connection succeeded """ if not self._expected_server_name: # We seem to connect the server anonymously, so SleekXMPP # couldn't find the server host name from the JID # => give it the given server host name as the expected one self._expected_server_name = host # Try to connect if super(BasicBot, self).connect( (host, port), reattempt, use_tls, use_ssl ): # On success, start the processing thread self.process(threaded=True) return True return False
python
def connect( self, host, port=5222, reattempt=False, use_tls=True, use_ssl=False ): # pylint: disable=W0221 """ Connects to the server. By default, uses an un-encrypted connection, as it won't connect to an OpenFire server otherwise :param host: Server host name :param port: Server port (default: 5222) :param reattempt: If True, tries to connect to the server until it succeeds :param use_tls: Use STARTTLS :param use_ssl: Server connection is encrypted :return: True if connection succeeded """ if not self._expected_server_name: # We seem to connect the server anonymously, so SleekXMPP # couldn't find the server host name from the JID # => give it the given server host name as the expected one self._expected_server_name = host # Try to connect if super(BasicBot, self).connect( (host, port), reattempt, use_tls, use_ssl ): # On success, start the processing thread self.process(threaded=True) return True return False
Connects to the server. By default, uses an un-encrypted connection, as it won't connect to an OpenFire server otherwise :param host: Server host name :param port: Server port (default: 5222) :param reattempt: If True, tries to connect to the server until it succeeds :param use_tls: Use STARTTLS :param use_ssl: Server connection is encrypted :return: True if connection succeeded
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/xmpp.py#L72-L104
tcalmant/ipopo
pelix/misc/xmpp.py
BasicBot.on_session_start
def on_session_start(self, data): # pylint: disable=W0613 """ XMPP session started """ # Send initial presence self.send_presence(ppriority=self._initial_priority) # Request roster self.get_roster()
python
def on_session_start(self, data): # pylint: disable=W0613 """ XMPP session started """ # Send initial presence self.send_presence(ppriority=self._initial_priority) # Request roster self.get_roster()
XMPP session started
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/xmpp.py#L106-L115
tcalmant/ipopo
pelix/misc/xmpp.py
InviteMixIn.on_invite
def on_invite(self, data): """ Multi-User Chat invite """ if not self._nick: self._nick = self.boundjid.user # Join the room self.plugin["xep_0045"].joinMUC(data["from"], self._nick)
python
def on_invite(self, data): """ Multi-User Chat invite """ if not self._nick: self._nick = self.boundjid.user # Join the room self.plugin["xep_0045"].joinMUC(data["from"], self._nick)
Multi-User Chat invite
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/xmpp.py#L154-L162
tcalmant/ipopo
pelix/misc/xmpp.py
ServiceDiscoveryMixin.iter_services
def iter_services(self, feature=None): """ Iterates over the root-level services on the server which provides the requested feature :param feature: Feature that the service must provide (optional) :return: A generator of services JID """ # Get the list of root services items = self["xep_0030"].get_items( jid=self.boundjid.domain, ifrom=self.boundjid.full, block=True, timeout=10, ) for item in items["disco_items"]["items"]: # Each item is a 3-tuple. The service JID is the first entry if not feature: # No filter yield item[0] else: # Get service details info = self["xep_0030"].get_info( jid=item[0], ifrom=self.boundjid.full, block=True, timeout=10, ) if feature in info["disco_info"]["features"]: # The service provides the required feature yield item[0]
python
def iter_services(self, feature=None): """ Iterates over the root-level services on the server which provides the requested feature :param feature: Feature that the service must provide (optional) :return: A generator of services JID """ # Get the list of root services items = self["xep_0030"].get_items( jid=self.boundjid.domain, ifrom=self.boundjid.full, block=True, timeout=10, ) for item in items["disco_items"]["items"]: # Each item is a 3-tuple. The service JID is the first entry if not feature: # No filter yield item[0] else: # Get service details info = self["xep_0030"].get_info( jid=item[0], ifrom=self.boundjid.full, block=True, timeout=10, ) if feature in info["disco_info"]["features"]: # The service provides the required feature yield item[0]
Iterates over the root-level services on the server which provides the requested feature :param feature: Feature that the service must provide (optional) :return: A generator of services JID
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/xmpp.py#L181-L212
tcalmant/ipopo
pelix/shell/parser.py
_find_assignment
def _find_assignment(arg_token): """ Find the first non-escaped assignment in the given argument token. Returns -1 if no assignment was found. :param arg_token: The argument token :return: The index of the first assignment, or -1 """ idx = arg_token.find("=") while idx != -1: if idx != 0 and arg_token[idx - 1] != "\\": # No escape character return idx idx = arg_token.find("=", idx + 1) # No assignment found return -1
python
def _find_assignment(arg_token): """ Find the first non-escaped assignment in the given argument token. Returns -1 if no assignment was found. :param arg_token: The argument token :return: The index of the first assignment, or -1 """ idx = arg_token.find("=") while idx != -1: if idx != 0 and arg_token[idx - 1] != "\\": # No escape character return idx idx = arg_token.find("=", idx + 1) # No assignment found return -1
Find the first non-escaped assignment in the given argument token. Returns -1 if no assignment was found. :param arg_token: The argument token :return: The index of the first assignment, or -1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L62-L79
tcalmant/ipopo
pelix/shell/parser.py
_make_args
def _make_args(args_list, session, fw_props): """ Converts the given list of arguments into a list (args) and a dictionary (kwargs). All arguments with an assignment are put into kwargs, others in args. :param args_list: The list of arguments to be treated :param session: The current shell session :return: The (arg_token, kwargs) tuple. """ args = [] kwargs = {} for arg_token in args_list: idx = _find_assignment(arg_token) if idx != -1: # Assignment key = arg_token[:idx] value = arg_token[idx + 1 :] kwargs[key] = value else: # Direct argument args.append(arg_token) # Prepare the dictionary of variables variables = collections.defaultdict(str) variables.update(fw_props) variables.update(session.variables) # Replace variables args = [_ArgTemplate(arg).safe_substitute(variables) for arg in args] kwargs = { key: _ArgTemplate(value).safe_substitute(variables) for key, value in kwargs.items() } return args, kwargs
python
def _make_args(args_list, session, fw_props): """ Converts the given list of arguments into a list (args) and a dictionary (kwargs). All arguments with an assignment are put into kwargs, others in args. :param args_list: The list of arguments to be treated :param session: The current shell session :return: The (arg_token, kwargs) tuple. """ args = [] kwargs = {} for arg_token in args_list: idx = _find_assignment(arg_token) if idx != -1: # Assignment key = arg_token[:idx] value = arg_token[idx + 1 :] kwargs[key] = value else: # Direct argument args.append(arg_token) # Prepare the dictionary of variables variables = collections.defaultdict(str) variables.update(fw_props) variables.update(session.variables) # Replace variables args = [_ArgTemplate(arg).safe_substitute(variables) for arg in args] kwargs = { key: _ArgTemplate(value).safe_substitute(variables) for key, value in kwargs.items() } return args, kwargs
Converts the given list of arguments into a list (args) and a dictionary (kwargs). All arguments with an assignment are put into kwargs, others in args. :param args_list: The list of arguments to be treated :param session: The current shell session :return: The (arg_token, kwargs) tuple.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L90-L125
tcalmant/ipopo
pelix/shell/parser.py
_split_ns_command
def _split_ns_command(cmd_token): """ Extracts the name space and the command name of the given command token. :param cmd_token: The command token :return: The extracted (name space, command) tuple """ namespace = None cmd_split = cmd_token.split(".", 1) if len(cmd_split) == 1: # No name space given command = cmd_split[0] else: # Got a name space and a command namespace = cmd_split[0] command = cmd_split[1] if not namespace: # No name space given: given an empty one namespace = "" # Use lower case values only return namespace.lower(), command.lower()
python
def _split_ns_command(cmd_token): """ Extracts the name space and the command name of the given command token. :param cmd_token: The command token :return: The extracted (name space, command) tuple """ namespace = None cmd_split = cmd_token.split(".", 1) if len(cmd_split) == 1: # No name space given command = cmd_split[0] else: # Got a name space and a command namespace = cmd_split[0] command = cmd_split[1] if not namespace: # No name space given: given an empty one namespace = "" # Use lower case values only return namespace.lower(), command.lower()
Extracts the name space and the command name of the given command token. :param cmd_token: The command token :return: The extracted (name space, command) tuple
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L128-L150
tcalmant/ipopo
pelix/shell/parser.py
Shell.register_command
def register_command(self, namespace, command, method): """ Registers the given command to the shell. The namespace can be None, empty or "default" :param namespace: The command name space. :param command: The shell name of the command :param method: The method to call :return: True if the method has been registered, False if it was already known or invalid """ if method is None: self._logger.error("No method given for %s.%s", namespace, command) return False # Store everything in lower case namespace = (namespace or "").strip().lower() command = (command or "").strip().lower() if not namespace: namespace = DEFAULT_NAMESPACE if not command: self._logger.error("No command name given") return False if namespace not in self._commands: space = self._commands[namespace] = {} else: space = self._commands[namespace] if command in space: self._logger.error( "Command already registered: %s.%s", namespace, command ) return False space[command] = method return True
python
def register_command(self, namespace, command, method): """ Registers the given command to the shell. The namespace can be None, empty or "default" :param namespace: The command name space. :param command: The shell name of the command :param method: The method to call :return: True if the method has been registered, False if it was already known or invalid """ if method is None: self._logger.error("No method given for %s.%s", namespace, command) return False # Store everything in lower case namespace = (namespace or "").strip().lower() command = (command or "").strip().lower() if not namespace: namespace = DEFAULT_NAMESPACE if not command: self._logger.error("No command name given") return False if namespace not in self._commands: space = self._commands[namespace] = {} else: space = self._commands[namespace] if command in space: self._logger.error( "Command already registered: %s.%s", namespace, command ) return False space[command] = method return True
Registers the given command to the shell. The namespace can be None, empty or "default" :param namespace: The command name space. :param command: The shell name of the command :param method: The method to call :return: True if the method has been registered, False if it was already known or invalid
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L204-L243
tcalmant/ipopo
pelix/shell/parser.py
Shell.get_command_completers
def get_command_completers(self, namespace, command): # type: (str, str) -> CompletionInfo """ Returns the completer method associated to the given command, or None :param namespace: The command name space. :param command: The shell name of the command :return: A CompletionConfiguration object :raise KeyError: Unknown command or name space """ # Find the method (can raise a KeyError) method = self._commands[namespace][command] # Return the completer, if any return getattr(method, ATTR_COMPLETERS, None)
python
def get_command_completers(self, namespace, command): # type: (str, str) -> CompletionInfo """ Returns the completer method associated to the given command, or None :param namespace: The command name space. :param command: The shell name of the command :return: A CompletionConfiguration object :raise KeyError: Unknown command or name space """ # Find the method (can raise a KeyError) method = self._commands[namespace][command] # Return the completer, if any return getattr(method, ATTR_COMPLETERS, None)
Returns the completer method associated to the given command, or None :param namespace: The command name space. :param command: The shell name of the command :return: A CompletionConfiguration object :raise KeyError: Unknown command or name space
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L245-L259
tcalmant/ipopo
pelix/shell/parser.py
Shell.unregister
def unregister(self, namespace, command=None): """ Unregisters the given command. If command is None, the whole name space is unregistered. :param namespace: The command name space. :param command: The shell name of the command, or None :return: True if the command was known, else False """ if not namespace: namespace = DEFAULT_NAMESPACE namespace = namespace.strip().lower() if namespace not in self._commands: self._logger.warning("Unknown name space: %s", namespace) return False if command is not None: # Remove the command command = command.strip().lower() if command not in self._commands[namespace]: self._logger.warning( "Unknown command: %s.%s", namespace, command ) return False del self._commands[namespace][command] # Remove the name space if necessary if not self._commands[namespace]: del self._commands[namespace] else: # Remove the whole name space del self._commands[namespace] return True
python
def unregister(self, namespace, command=None): """ Unregisters the given command. If command is None, the whole name space is unregistered. :param namespace: The command name space. :param command: The shell name of the command, or None :return: True if the command was known, else False """ if not namespace: namespace = DEFAULT_NAMESPACE namespace = namespace.strip().lower() if namespace not in self._commands: self._logger.warning("Unknown name space: %s", namespace) return False if command is not None: # Remove the command command = command.strip().lower() if command not in self._commands[namespace]: self._logger.warning( "Unknown command: %s.%s", namespace, command ) return False del self._commands[namespace][command] # Remove the name space if necessary if not self._commands[namespace]: del self._commands[namespace] else: # Remove the whole name space del self._commands[namespace] return True
Unregisters the given command. If command is None, the whole name space is unregistered. :param namespace: The command name space. :param command: The shell name of the command, or None :return: True if the command was known, else False
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L261-L296
tcalmant/ipopo
pelix/shell/parser.py
Shell.__find_command_ns
def __find_command_ns(self, command): """ Returns the name spaces where the given command named is registered. If the command exists in the default name space, the returned list will only contain the default name space. Returns an empty list of the command is unknown :param command: A command name :return: A list of name spaces """ # Look for the spaces where the command name appears namespaces = [] for namespace, commands in self._commands.items(): if command in commands: namespaces.append(namespace) # Sort name spaces namespaces.sort() # Default name space must always come first try: namespaces.remove(DEFAULT_NAMESPACE) namespaces.insert(0, DEFAULT_NAMESPACE) except ValueError: # Default name space wasn't present pass return namespaces
python
def __find_command_ns(self, command): """ Returns the name spaces where the given command named is registered. If the command exists in the default name space, the returned list will only contain the default name space. Returns an empty list of the command is unknown :param command: A command name :return: A list of name spaces """ # Look for the spaces where the command name appears namespaces = [] for namespace, commands in self._commands.items(): if command in commands: namespaces.append(namespace) # Sort name spaces namespaces.sort() # Default name space must always come first try: namespaces.remove(DEFAULT_NAMESPACE) namespaces.insert(0, DEFAULT_NAMESPACE) except ValueError: # Default name space wasn't present pass return namespaces
Returns the name spaces where the given command named is registered. If the command exists in the default name space, the returned list will only contain the default name space. Returns an empty list of the command is unknown :param command: A command name :return: A list of name spaces
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L298-L325
tcalmant/ipopo
pelix/shell/parser.py
Shell.get_namespaces
def get_namespaces(self): """ Retrieves the list of known name spaces (without the default one) :return: The list of known name spaces """ namespaces = list(self._commands.keys()) namespaces.remove(DEFAULT_NAMESPACE) namespaces.sort() return namespaces
python
def get_namespaces(self): """ Retrieves the list of known name spaces (without the default one) :return: The list of known name spaces """ namespaces = list(self._commands.keys()) namespaces.remove(DEFAULT_NAMESPACE) namespaces.sort() return namespaces
Retrieves the list of known name spaces (without the default one) :return: The list of known name spaces
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L327-L336
tcalmant/ipopo
pelix/shell/parser.py
Shell.get_commands
def get_commands(self, namespace): """ Retrieves the commands of the given name space. If *namespace* is None or empty, it retrieves the commands of the default name space :param namespace: The commands name space :return: A list of commands names """ if not namespace: # Default name space: namespace = DEFAULT_NAMESPACE try: namespace.strip().lower() commands = list(self._commands[namespace].keys()) commands.sort() return commands except KeyError: # Unknown name space return []
python
def get_commands(self, namespace): """ Retrieves the commands of the given name space. If *namespace* is None or empty, it retrieves the commands of the default name space :param namespace: The commands name space :return: A list of commands names """ if not namespace: # Default name space: namespace = DEFAULT_NAMESPACE try: namespace.strip().lower() commands = list(self._commands[namespace].keys()) commands.sort() return commands except KeyError: # Unknown name space return []
Retrieves the commands of the given name space. If *namespace* is None or empty, it retrieves the commands of the default name space :param namespace: The commands name space :return: A list of commands names
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L338-L357
tcalmant/ipopo
pelix/shell/parser.py
Shell.get_ns_commands
def get_ns_commands(self, cmd_name): """ Retrieves the possible name spaces and commands associated to the given command name. :param cmd_name: The given command name :return: A list of 2-tuples (name space, command) :raise ValueError: Unknown command name """ namespace, command = _split_ns_command(cmd_name) if not namespace: # Name space not given, look for the commands spaces = self.__find_command_ns(command) if not spaces: # Unknown command raise ValueError("Unknown command {0}".format(command)) else: # Return a sorted list of tuples return sorted((namespace, command) for namespace in spaces) # Single match return [(namespace, command)]
python
def get_ns_commands(self, cmd_name): """ Retrieves the possible name spaces and commands associated to the given command name. :param cmd_name: The given command name :return: A list of 2-tuples (name space, command) :raise ValueError: Unknown command name """ namespace, command = _split_ns_command(cmd_name) if not namespace: # Name space not given, look for the commands spaces = self.__find_command_ns(command) if not spaces: # Unknown command raise ValueError("Unknown command {0}".format(command)) else: # Return a sorted list of tuples return sorted((namespace, command) for namespace in spaces) # Single match return [(namespace, command)]
Retrieves the possible name spaces and commands associated to the given command name. :param cmd_name: The given command name :return: A list of 2-tuples (name space, command) :raise ValueError: Unknown command name
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L359-L380
tcalmant/ipopo
pelix/shell/parser.py
Shell.get_ns_command
def get_ns_command(self, cmd_name): """ Retrieves the name space and the command associated to the given command name. :param cmd_name: The given command name :return: A 2-tuple (name space, command) :raise ValueError: Unknown command name """ namespace, command = _split_ns_command(cmd_name) if not namespace: # Name space not given, look for the command spaces = self.__find_command_ns(command) if not spaces: # Unknown command raise ValueError("Unknown command {0}".format(command)) elif len(spaces) > 1: # Multiple possibilities if spaces[0] == DEFAULT_NAMESPACE: # Default name space has priority namespace = DEFAULT_NAMESPACE else: # Ambiguous name raise ValueError( "Multiple name spaces for command '{0}': {1}".format( command, ", ".join(sorted(spaces)) ) ) else: # Use the found name space namespace = spaces[0] # Command found return namespace, command
python
def get_ns_command(self, cmd_name): """ Retrieves the name space and the command associated to the given command name. :param cmd_name: The given command name :return: A 2-tuple (name space, command) :raise ValueError: Unknown command name """ namespace, command = _split_ns_command(cmd_name) if not namespace: # Name space not given, look for the command spaces = self.__find_command_ns(command) if not spaces: # Unknown command raise ValueError("Unknown command {0}".format(command)) elif len(spaces) > 1: # Multiple possibilities if spaces[0] == DEFAULT_NAMESPACE: # Default name space has priority namespace = DEFAULT_NAMESPACE else: # Ambiguous name raise ValueError( "Multiple name spaces for command '{0}': {1}".format( command, ", ".join(sorted(spaces)) ) ) else: # Use the found name space namespace = spaces[0] # Command found return namespace, command
Retrieves the name space and the command associated to the given command name. :param cmd_name: The given command name :return: A 2-tuple (name space, command) :raise ValueError: Unknown command name
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L382-L416
tcalmant/ipopo
pelix/shell/parser.py
Shell.execute
def execute(self, cmdline, session=None): """ Executes the command corresponding to the given line :param cmdline: Command line to parse :param session: Current shell session :return: True if command succeeded, else False """ if session is None: # Default session session = beans.ShellSession( beans.IOHandler(sys.stdin, sys.stdout), {} ) assert isinstance(session, beans.ShellSession) # Split the command line if not cmdline: return False # Convert the line into a string cmdline = to_str(cmdline) try: line_split = shlex.split(cmdline, True, True) except ValueError as ex: session.write_line("Error reading line: {0}", ex) return False if not line_split: return False try: # Extract command information namespace, command = self.get_ns_command(line_split[0]) except ValueError as ex: # Unknown command session.write_line(str(ex)) return False # Get the content of the name space space = self._commands.get(namespace, None) if not space: session.write_line("Unknown name space {0}", namespace) return False # Get the method object method = space.get(command, None) if method is None: session.write_line("Unknown command: {0}.{1}", namespace, command) return False # Make arguments and keyword arguments args, kwargs = _make_args( line_split[1:], session, self._framework.get_properties() ) try: # Execute it result = method(session, *args, **kwargs) # Store the result as $? if result is not None: session.set(beans.RESULT_VAR_NAME, result) # 0, None are considered as success, so don't use not nor bool return result is not False except TypeError as ex: # Invalid arguments... self._logger.error( "Error calling %s.%s: %s", namespace, command, ex ) session.write_line("Invalid method call: {0}", ex) self.__print_namespace_help(session, namespace, command) return False except Exception as ex: # Error self._logger.exception( "Error calling %s.%s: %s", namespace, command, ex ) session.write_line("{0}: {1}", type(ex).__name__, str(ex)) return False finally: # Try to flush in any case try: session.flush() except IOError: pass
python
def execute(self, cmdline, session=None): """ Executes the command corresponding to the given line :param cmdline: Command line to parse :param session: Current shell session :return: True if command succeeded, else False """ if session is None: # Default session session = beans.ShellSession( beans.IOHandler(sys.stdin, sys.stdout), {} ) assert isinstance(session, beans.ShellSession) # Split the command line if not cmdline: return False # Convert the line into a string cmdline = to_str(cmdline) try: line_split = shlex.split(cmdline, True, True) except ValueError as ex: session.write_line("Error reading line: {0}", ex) return False if not line_split: return False try: # Extract command information namespace, command = self.get_ns_command(line_split[0]) except ValueError as ex: # Unknown command session.write_line(str(ex)) return False # Get the content of the name space space = self._commands.get(namespace, None) if not space: session.write_line("Unknown name space {0}", namespace) return False # Get the method object method = space.get(command, None) if method is None: session.write_line("Unknown command: {0}.{1}", namespace, command) return False # Make arguments and keyword arguments args, kwargs = _make_args( line_split[1:], session, self._framework.get_properties() ) try: # Execute it result = method(session, *args, **kwargs) # Store the result as $? if result is not None: session.set(beans.RESULT_VAR_NAME, result) # 0, None are considered as success, so don't use not nor bool return result is not False except TypeError as ex: # Invalid arguments... self._logger.error( "Error calling %s.%s: %s", namespace, command, ex ) session.write_line("Invalid method call: {0}", ex) self.__print_namespace_help(session, namespace, command) return False except Exception as ex: # Error self._logger.exception( "Error calling %s.%s: %s", namespace, command, ex ) session.write_line("{0}: {1}", type(ex).__name__, str(ex)) return False finally: # Try to flush in any case try: session.flush() except IOError: pass
Executes the command corresponding to the given line :param cmdline: Command line to parse :param session: Current shell session :return: True if command succeeded, else False
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L418-L504
tcalmant/ipopo
pelix/shell/parser.py
Shell.__extract_help
def __extract_help(method): """ Formats the help string for the given method :param method: The method to document :return: A tuple: (arguments list, documentation line) """ if method is None: return "(No associated method)" # Get the arguments arg_spec = get_method_arguments(method) # Ignore the session argument start_arg = 1 # Compute the number of arguments with default value if arg_spec.defaults is not None: nb_optional = len(arg_spec.defaults) # Let the mandatory arguments as they are args = [ "<{0}>".format(arg) for arg in arg_spec.args[start_arg:-nb_optional] ] # Add the other arguments for name, value in zip( arg_spec.args[-nb_optional:], arg_spec.defaults[-nb_optional:] ): if value is not None: args.append("[<{0}>={1}]".format(name, value)) else: args.append("[<{0}>]".format(name)) else: # All arguments are mandatory args = ["<{0}>".format(arg) for arg in arg_spec.args[start_arg:]] # Extra arguments if arg_spec.keywords: args.append("[<property=value> ...]") if arg_spec.varargs: args.append("[<{0} ...>]".format(arg_spec.varargs)) # Get the documentation string doc = inspect.getdoc(method) or "(Documentation missing)" return " ".join(args), " ".join(doc.split())
python
def __extract_help(method): """ Formats the help string for the given method :param method: The method to document :return: A tuple: (arguments list, documentation line) """ if method is None: return "(No associated method)" # Get the arguments arg_spec = get_method_arguments(method) # Ignore the session argument start_arg = 1 # Compute the number of arguments with default value if arg_spec.defaults is not None: nb_optional = len(arg_spec.defaults) # Let the mandatory arguments as they are args = [ "<{0}>".format(arg) for arg in arg_spec.args[start_arg:-nb_optional] ] # Add the other arguments for name, value in zip( arg_spec.args[-nb_optional:], arg_spec.defaults[-nb_optional:] ): if value is not None: args.append("[<{0}>={1}]".format(name, value)) else: args.append("[<{0}>]".format(name)) else: # All arguments are mandatory args = ["<{0}>".format(arg) for arg in arg_spec.args[start_arg:]] # Extra arguments if arg_spec.keywords: args.append("[<property=value> ...]") if arg_spec.varargs: args.append("[<{0} ...>]".format(arg_spec.varargs)) # Get the documentation string doc = inspect.getdoc(method) or "(Documentation missing)" return " ".join(args), " ".join(doc.split())
Formats the help string for the given method :param method: The method to document :return: A tuple: (arguments list, documentation line)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L507-L554
tcalmant/ipopo
pelix/shell/parser.py
Shell.__print_command_help
def __print_command_help(self, session, namespace, cmd_name): """ Prints the documentation of the given command :param session: Session handler :param namespace: Name space of the command :param cmd_name: Name of the command """ # Extract documentation args, doc = self.__extract_help(self._commands[namespace][cmd_name]) # Print the command name, and its arguments if args: session.write_line("- {0} {1}", cmd_name, args) else: session.write_line("- {0}", cmd_name) # Print the documentation line session.write_line("\t\t{0}", doc)
python
def __print_command_help(self, session, namespace, cmd_name): """ Prints the documentation of the given command :param session: Session handler :param namespace: Name space of the command :param cmd_name: Name of the command """ # Extract documentation args, doc = self.__extract_help(self._commands[namespace][cmd_name]) # Print the command name, and its arguments if args: session.write_line("- {0} {1}", cmd_name, args) else: session.write_line("- {0}", cmd_name) # Print the documentation line session.write_line("\t\t{0}", doc)
Prints the documentation of the given command :param session: Session handler :param namespace: Name space of the command :param cmd_name: Name of the command
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L556-L574
tcalmant/ipopo
pelix/shell/parser.py
Shell.__print_namespace_help
def __print_namespace_help(self, session, namespace, cmd_name=None): """ Prints the documentation of all the commands in the given name space, or only of the given command :param session: Session Handler :param namespace: Name space of the command :param cmd_name: Name of the command to show, None to show them all """ session.write_line("=== Name space '{0}' ===", namespace) # Get all commands in this name space if cmd_name is None: names = [command for command in self._commands[namespace]] names.sort() else: names = [cmd_name] first_cmd = True for command in names: if not first_cmd: # Print an empty line session.write_line("\n") self.__print_command_help(session, namespace, command) first_cmd = False
python
def __print_namespace_help(self, session, namespace, cmd_name=None): """ Prints the documentation of all the commands in the given name space, or only of the given command :param session: Session Handler :param namespace: Name space of the command :param cmd_name: Name of the command to show, None to show them all """ session.write_line("=== Name space '{0}' ===", namespace) # Get all commands in this name space if cmd_name is None: names = [command for command in self._commands[namespace]] names.sort() else: names = [cmd_name] first_cmd = True for command in names: if not first_cmd: # Print an empty line session.write_line("\n") self.__print_command_help(session, namespace, command) first_cmd = False
Prints the documentation of all the commands in the given name space, or only of the given command :param session: Session Handler :param namespace: Name space of the command :param cmd_name: Name of the command to show, None to show them all
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L576-L601
tcalmant/ipopo
pelix/shell/parser.py
Shell.print_help
def print_help(self, session, command=None): """ Prints the available methods and their documentation, or the documentation of the given command. """ if command: # Single command mode if command in self._commands: # Argument is a name space self.__print_namespace_help(session, command) was_namespace = True else: was_namespace = False # Also print the name of matching commands try: # Extract command name space and name possibilities = self.get_ns_commands(command) except ValueError as ex: # Unknown command if not was_namespace: # ... and no name space were matching either -> error session.write_line(str(ex)) return False else: # Print the help of the found command if was_namespace: # Give some space session.write_line("\n\n") for namespace, cmd_name in possibilities: self.__print_namespace_help(session, namespace, cmd_name) else: # Get all name spaces namespaces = list(self._commands.keys()) namespaces.remove(DEFAULT_NAMESPACE) namespaces.sort() namespaces.insert(0, DEFAULT_NAMESPACE) first_ns = True for namespace in namespaces: if not first_ns: # Add empty lines session.write_line("\n\n") # Print the help of all commands self.__print_namespace_help(session, namespace) first_ns = False return None
python
def print_help(self, session, command=None): """ Prints the available methods and their documentation, or the documentation of the given command. """ if command: # Single command mode if command in self._commands: # Argument is a name space self.__print_namespace_help(session, command) was_namespace = True else: was_namespace = False # Also print the name of matching commands try: # Extract command name space and name possibilities = self.get_ns_commands(command) except ValueError as ex: # Unknown command if not was_namespace: # ... and no name space were matching either -> error session.write_line(str(ex)) return False else: # Print the help of the found command if was_namespace: # Give some space session.write_line("\n\n") for namespace, cmd_name in possibilities: self.__print_namespace_help(session, namespace, cmd_name) else: # Get all name spaces namespaces = list(self._commands.keys()) namespaces.remove(DEFAULT_NAMESPACE) namespaces.sort() namespaces.insert(0, DEFAULT_NAMESPACE) first_ns = True for namespace in namespaces: if not first_ns: # Add empty lines session.write_line("\n\n") # Print the help of all commands self.__print_namespace_help(session, namespace) first_ns = False return None
Prints the available methods and their documentation, or the documentation of the given command.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L603-L652
tcalmant/ipopo
pelix/shell/parser.py
Shell.var_set
def var_set(session, **kwargs): """ Sets the given variables or prints the current ones. "set answer=42" """ if not kwargs: for name, value in session.variables.items(): session.write_line("{0}={1}".format(name, value)) else: for name, value in kwargs.items(): name = name.strip() session.set(name, value) session.write_line("{0}={1}", name, value)
python
def var_set(session, **kwargs): """ Sets the given variables or prints the current ones. "set answer=42" """ if not kwargs: for name, value in session.variables.items(): session.write_line("{0}={1}".format(name, value)) else: for name, value in kwargs.items(): name = name.strip() session.set(name, value) session.write_line("{0}={1}", name, value)
Sets the given variables or prints the current ones. "set answer=42"
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L670-L681
tcalmant/ipopo
pelix/shell/parser.py
Shell.var_unset
def var_unset(session, name): """ Unsets the given variable """ name = name.strip() try: session.unset(name) except KeyError: session.write_line("Unknown variable: {0}", name) return False else: session.write_line("Variable {0} unset.", name) return None
python
def var_unset(session, name): """ Unsets the given variable """ name = name.strip() try: session.unset(name) except KeyError: session.write_line("Unknown variable: {0}", name) return False else: session.write_line("Variable {0} unset.", name) return None
Unsets the given variable
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L684-L697
tcalmant/ipopo
pelix/shell/parser.py
Shell.run_file
def run_file(self, session, filename): """ Runs the given "script" file """ try: with open(filename, "r") as filep: for lineno, line in enumerate(filep): line = line.strip() if not line or line.startswith("#"): # Ignore comments and empty lines continue # Print out the executed line session.write_line("[{0:02d}] >> {1}", lineno, line) # Execute the line if not self.execute(line, session): session.write_line( "Command at line {0} failed. Abandon.", lineno + 1 ) return False session.write_line("Script execution succeeded") except IOError as ex: session.write_line("Error reading file {0}: {1}", filename, ex) return False return None
python
def run_file(self, session, filename): """ Runs the given "script" file """ try: with open(filename, "r") as filep: for lineno, line in enumerate(filep): line = line.strip() if not line or line.startswith("#"): # Ignore comments and empty lines continue # Print out the executed line session.write_line("[{0:02d}] >> {1}", lineno, line) # Execute the line if not self.execute(line, session): session.write_line( "Command at line {0} failed. Abandon.", lineno + 1 ) return False session.write_line("Script execution succeeded") except IOError as ex: session.write_line("Error reading file {0}: {1}", filename, ex) return False return None
Runs the given "script" file
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/parser.py#L699-L726
tcalmant/ipopo
pelix/remote/xml_rpc.py
_XmlRpcServlet._simple_dispatch
def _simple_dispatch(self, name, params): """ Dispatch method """ try: # Internal method return self.funcs[name](*params) except KeyError: # Other method pass # Call the other method outside the except block, to avoid messy logs # in case of error return self._dispatch_method(name, params)
python
def _simple_dispatch(self, name, params): """ Dispatch method """ try: # Internal method return self.funcs[name](*params) except KeyError: # Other method pass # Call the other method outside the except block, to avoid messy logs # in case of error return self._dispatch_method(name, params)
Dispatch method
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/xml_rpc.py#L104-L117
tcalmant/ipopo
pelix/misc/init_handler.py
_Configuration.add_properties
def add_properties(self, properties): """ Updates the framework properties dictionary :param properties: New framework properties to add """ if isinstance(properties, dict): self._properties.update(properties)
python
def add_properties(self, properties): """ Updates the framework properties dictionary :param properties: New framework properties to add """ if isinstance(properties, dict): self._properties.update(properties)
Updates the framework properties dictionary :param properties: New framework properties to add
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L108-L115
tcalmant/ipopo
pelix/misc/init_handler.py
_Configuration.add_environment
def add_environment(self, environ): """ Updates the environment dictionary with the given one. Existing entries are overridden by the given ones :param environ: New environment variables """ if isinstance(environ, dict): self._environment.update(environ)
python
def add_environment(self, environ): """ Updates the environment dictionary with the given one. Existing entries are overridden by the given ones :param environ: New environment variables """ if isinstance(environ, dict): self._environment.update(environ)
Updates the environment dictionary with the given one. Existing entries are overridden by the given ones :param environ: New environment variables
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L126-L135
tcalmant/ipopo
pelix/misc/init_handler.py
_Configuration.add_paths
def add_paths(self, paths): """ Adds entries to the Python path. The given paths are normalized before being added to the left of the list :param paths: New paths to add """ if paths: # Use new paths in priority self._paths = list(paths) + self._paths
python
def add_paths(self, paths): """ Adds entries to the Python path. The given paths are normalized before being added to the left of the list :param paths: New paths to add """ if paths: # Use new paths in priority self._paths = list(paths) + self._paths
Adds entries to the Python path. The given paths are normalized before being added to the left of the list :param paths: New paths to add
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L147-L158
tcalmant/ipopo
pelix/misc/init_handler.py
_Configuration.add_components
def add_components(self, components): """ Adds a list of components to instantiate :param components: The description of components :raise KeyError: Missing component configuration """ if components: for component in components: self._components[component["name"]] = ( component["factory"], component.get("properties", {}), )
python
def add_components(self, components): """ Adds a list of components to instantiate :param components: The description of components :raise KeyError: Missing component configuration """ if components: for component in components: self._components[component["name"]] = ( component["factory"], component.get("properties", {}), )
Adds a list of components to instantiate :param components: The description of components :raise KeyError: Missing component configuration
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L198-L210
tcalmant/ipopo
pelix/misc/init_handler.py
_Configuration.normalize
def normalize(self): """ Normalizes environment variables, paths and filters the lists of bundles to install and start. After this call, the environment variables of this process will have been updated. """ # Add environment variables os.environ.update(self._environment) # Normalize paths and avoid duplicates self._paths = remove_duplicates( os.path.realpath(os.path.expanduser(os.path.expandvars(path))) for path in self._paths if os.path.exists(path) ) # Normalize the lists of bundles self._bundles = remove_duplicates(self._bundles)
python
def normalize(self): """ Normalizes environment variables, paths and filters the lists of bundles to install and start. After this call, the environment variables of this process will have been updated. """ # Add environment variables os.environ.update(self._environment) # Normalize paths and avoid duplicates self._paths = remove_duplicates( os.path.realpath(os.path.expanduser(os.path.expandvars(path))) for path in self._paths if os.path.exists(path) ) # Normalize the lists of bundles self._bundles = remove_duplicates(self._bundles)
Normalizes environment variables, paths and filters the lists of bundles to install and start. After this call, the environment variables of this process will have been updated.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L223-L242
tcalmant/ipopo
pelix/misc/init_handler.py
InitFileHandler.find_default
def find_default(self, filename): """ A generate which looks in common folders for the default configuration file. The paths goes from system defaults to user specific files. :param filename: The name of the file to find :return: The complete path to the found files """ for path in self.DEFAULT_PATH: # Normalize path path = os.path.expanduser(os.path.expandvars(path)) fullname = os.path.realpath(os.path.join(path, filename)) if os.path.exists(fullname) and os.path.isfile(fullname): yield fullname
python
def find_default(self, filename): """ A generate which looks in common folders for the default configuration file. The paths goes from system defaults to user specific files. :param filename: The name of the file to find :return: The complete path to the found files """ for path in self.DEFAULT_PATH: # Normalize path path = os.path.expanduser(os.path.expandvars(path)) fullname = os.path.realpath(os.path.join(path, filename)) if os.path.exists(fullname) and os.path.isfile(fullname): yield fullname
A generate which looks in common folders for the default configuration file. The paths goes from system defaults to user specific files. :param filename: The name of the file to find :return: The complete path to the found files
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L289-L303
tcalmant/ipopo
pelix/misc/init_handler.py
InitFileHandler.load
def load(self, filename=None): """ Loads the given file and adds its content to the current state. This method can be called multiple times to merge different files. If no filename is given, this method loads all default files found. It returns False if no default configuration file has been found :param filename: The file to load :return: True if the file has been correctly parsed, False if no file was given and no default file exist :raise IOError: Error loading file """ if not filename: for name in self.find_default(".pelix.conf"): self.load(name) else: with open(filename, "r") as filep: self.__parse(json.load(filep))
python
def load(self, filename=None): """ Loads the given file and adds its content to the current state. This method can be called multiple times to merge different files. If no filename is given, this method loads all default files found. It returns False if no default configuration file has been found :param filename: The file to load :return: True if the file has been correctly parsed, False if no file was given and no default file exist :raise IOError: Error loading file """ if not filename: for name in self.find_default(".pelix.conf"): self.load(name) else: with open(filename, "r") as filep: self.__parse(json.load(filep))
Loads the given file and adds its content to the current state. This method can be called multiple times to merge different files. If no filename is given, this method loads all default files found. It returns False if no default configuration file has been found :param filename: The file to load :return: True if the file has been correctly parsed, False if no file was given and no default file exist :raise IOError: Error loading file
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L305-L323
tcalmant/ipopo
pelix/misc/init_handler.py
InitFileHandler.__parse
def __parse(self, configuration): """ Parses the given configuration dictionary :param configuration: A configuration as a dictionary (JSON object) """ for entry in ( "properties", "environment", "paths", "bundles", "components", ): # Check if current values must be reset reset_key = "reset_{0}".format(entry) # Compute the name of the method call_name = "add" if not configuration.get(reset_key) else "set" method = getattr(self.__state, "{0}_{1}".format(call_name, entry)) # Update configuration method(configuration.get(entry))
python
def __parse(self, configuration): """ Parses the given configuration dictionary :param configuration: A configuration as a dictionary (JSON object) """ for entry in ( "properties", "environment", "paths", "bundles", "components", ): # Check if current values must be reset reset_key = "reset_{0}".format(entry) # Compute the name of the method call_name = "add" if not configuration.get(reset_key) else "set" method = getattr(self.__state, "{0}_{1}".format(call_name, entry)) # Update configuration method(configuration.get(entry))
Parses the given configuration dictionary :param configuration: A configuration as a dictionary (JSON object)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L325-L346
tcalmant/ipopo
pelix/misc/init_handler.py
InitFileHandler.normalize
def normalize(self): """ Normalizes environment variables and the Python path. This method first updates the environment variables (``os.environ``). Then, it normalizes the Python path (``sys.path``) by resolving all references to the user directory and environment variables. """ # Normalize configuration self.__state.normalize() # Update sys.path, avoiding duplicates whole_path = list(self.__state.paths) whole_path.extend(sys.path) # Ensure the working directory as first search path sys.path = ["."] for path in whole_path: if path not in sys.path: sys.path.append(path)
python
def normalize(self): """ Normalizes environment variables and the Python path. This method first updates the environment variables (``os.environ``). Then, it normalizes the Python path (``sys.path``) by resolving all references to the user directory and environment variables. """ # Normalize configuration self.__state.normalize() # Update sys.path, avoiding duplicates whole_path = list(self.__state.paths) whole_path.extend(sys.path) # Ensure the working directory as first search path sys.path = ["."] for path in whole_path: if path not in sys.path: sys.path.append(path)
Normalizes environment variables and the Python path. This method first updates the environment variables (``os.environ``). Then, it normalizes the Python path (``sys.path``) by resolving all references to the user directory and environment variables.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L348-L367
tcalmant/ipopo
pelix/misc/init_handler.py
InitFileHandler.instantiate_components
def instantiate_components(self, context): """ Instantiate the defined components .. note:: This method requires the iPOPO core service to be registered. This means that the ``pelix.ipopo.core`` must have been declared in the list of bundles (or installed and started programmatically). :param context: A :class:`~pelix.framework.BundleContext` object :raise BundleException: Error looking for the iPOPO service or starting a component """ with use_ipopo(context) as ipopo: for name, (factory, properties) in self.__state.components.items(): ipopo.instantiate(factory, name, properties)
python
def instantiate_components(self, context): """ Instantiate the defined components .. note:: This method requires the iPOPO core service to be registered. This means that the ``pelix.ipopo.core`` must have been declared in the list of bundles (or installed and started programmatically). :param context: A :class:`~pelix.framework.BundleContext` object :raise BundleException: Error looking for the iPOPO service or starting a component """ with use_ipopo(context) as ipopo: for name, (factory, properties) in self.__state.components.items(): ipopo.instantiate(factory, name, properties)
Instantiate the defined components .. note:: This method requires the iPOPO core service to be registered. This means that the ``pelix.ipopo.core`` must have been declared in the list of bundles (or installed and started programmatically). :param context: A :class:`~pelix.framework.BundleContext` object :raise BundleException: Error looking for the iPOPO service or starting a component
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/init_handler.py#L369-L384
moskytw/uniout
_uniout.py
literalize_string
def literalize_string(content, is_unicode=False): r'''Literalize a string content. Examples: >>> print literalize_string('str') 'str' >>> print literalize_string('\'str\'') "'str'" >>> print literalize_string('\"\'str\'\"') '"\'str\'"' ''' quote_mark = "'" if "'" in content: quote_mark = '"' if '"' in content: quote_mark = "'" content = content.replace(r"'", r"\'") if '\n' in content: quote_mark *= 3 return 'u'[not is_unicode:]+quote_mark+content+quote_mark
python
def literalize_string(content, is_unicode=False): r'''Literalize a string content. Examples: >>> print literalize_string('str') 'str' >>> print literalize_string('\'str\'') "'str'" >>> print literalize_string('\"\'str\'\"') '"\'str\'"' ''' quote_mark = "'" if "'" in content: quote_mark = '"' if '"' in content: quote_mark = "'" content = content.replace(r"'", r"\'") if '\n' in content: quote_mark *= 3 return 'u'[not is_unicode:]+quote_mark+content+quote_mark
r'''Literalize a string content. Examples: >>> print literalize_string('str') 'str' >>> print literalize_string('\'str\'') "'str'" >>> print literalize_string('\"\'str\'\"') '"\'str\'"'
https://github.com/moskytw/uniout/blob/8ea8fc84f3da297352e6b7335e354b41b40e7788/_uniout.py#L9-L32
moskytw/uniout
_uniout.py
unescape_string_literal
def unescape_string_literal(literal, encoding): r'''Unescape a string or unicode literal. Examples: >>> u = u'\u4e16\u754c\u4f60\u597d' # 世界你好 >>> print unescape_string_literal(repr(u), 'utf-8') u'世界你好' >>> print unescape_string_literal(repr(u.encode('utf-8')), 'utf-8') '世界你好' >>> print unescape_string_literal(repr(u.encode('big5')), 'utf-8') '\xa5@\xac\xc9\xa7A\xa6n' ''' if encoding is None: encoding = getfilesystemencoding() if literal[0] in 'uU': return literalize_string( literal[2:-1].decode('unicode-escape').encode(encoding), is_unicode=True ) else: content = literal[1:-1].decode('string-escape') # keep it escaped if the encoding doesn't work on it try: content.decode(encoding) except UnicodeDecodeError: return literal return literalize_string(content)
python
def unescape_string_literal(literal, encoding): r'''Unescape a string or unicode literal. Examples: >>> u = u'\u4e16\u754c\u4f60\u597d' # 世界你好 >>> print unescape_string_literal(repr(u), 'utf-8') u'世界你好' >>> print unescape_string_literal(repr(u.encode('utf-8')), 'utf-8') '世界你好' >>> print unescape_string_literal(repr(u.encode('big5')), 'utf-8') '\xa5@\xac\xc9\xa7A\xa6n' ''' if encoding is None: encoding = getfilesystemencoding() if literal[0] in 'uU': return literalize_string( literal[2:-1].decode('unicode-escape').encode(encoding), is_unicode=True ) else: content = literal[1:-1].decode('string-escape') # keep it escaped if the encoding doesn't work on it try: content.decode(encoding) except UnicodeDecodeError: return literal return literalize_string(content)
r'''Unescape a string or unicode literal. Examples: >>> u = u'\u4e16\u754c\u4f60\u597d' # 世界你好 >>> print unescape_string_literal(repr(u), 'utf-8') u'世界你好' >>> print unescape_string_literal(repr(u.encode('utf-8')), 'utf-8') '世界你好' >>> print unescape_string_literal(repr(u.encode('big5')), 'utf-8') '\xa5@\xac\xc9\xa7A\xa6n'
https://github.com/moskytw/uniout/blob/8ea8fc84f3da297352e6b7335e354b41b40e7788/_uniout.py#L38-L74
moskytw/uniout
_uniout.py
unescape
def unescape(b, encoding): '''Unescape all string and unicode literals in bytes.''' return string_literal_re.sub( lambda m: unescape_string_literal(m.group(), encoding), b )
python
def unescape(b, encoding): '''Unescape all string and unicode literals in bytes.''' return string_literal_re.sub( lambda m: unescape_string_literal(m.group(), encoding), b )
Unescape all string and unicode literals in bytes.
https://github.com/moskytw/uniout/blob/8ea8fc84f3da297352e6b7335e354b41b40e7788/_uniout.py#L77-L82
moskytw/uniout
_uniout.py
make_unistream
def make_unistream(stream): '''Make a stream which unescapes string literals before writes out.''' unistream = lambda: 'I am an unistream!' # make unistream look like the stream for attr_name in dir(stream): if not attr_name.startswith('_'): setattr(unistream, attr_name, getattr(stream, attr_name)) # modify the write method to unescape the output unistream.write = lambda b: stream.write( # TODO: the to_bytes makes the behavior different, should we care? unescape(to_bytes(b, unistream.encoding), unistream.encoding) ) return unistream
python
def make_unistream(stream): '''Make a stream which unescapes string literals before writes out.''' unistream = lambda: 'I am an unistream!' # make unistream look like the stream for attr_name in dir(stream): if not attr_name.startswith('_'): setattr(unistream, attr_name, getattr(stream, attr_name)) # modify the write method to unescape the output unistream.write = lambda b: stream.write( # TODO: the to_bytes makes the behavior different, should we care? unescape(to_bytes(b, unistream.encoding), unistream.encoding) ) return unistream
Make a stream which unescapes string literals before writes out.
https://github.com/moskytw/uniout/blob/8ea8fc84f3da297352e6b7335e354b41b40e7788/_uniout.py#L96-L112
tcalmant/ipopo
pelix/shell/report.py
format_frame_info
def format_frame_info(frame): """ Formats the given stack frame to show its position in the code and part of its context :param frame: A stack frame """ # Same as in traceback.extract_stack line_no = frame.f_lineno code = frame.f_code filename = code.co_filename method_name = code.co_name linecache.checkcache(filename) try: # Try to get the type of the calling object instance = frame.f_locals["self"] method_name = "{0}::{1}".format(type(instance).__name__, method_name) except KeyError: # Not called from a bound method pass # File & line output_lines = [ ' File "{0}", line {1}, in {2}'.format(filename, line_no, method_name) ] # Arguments if frame.f_locals: # Pypy keeps f_locals as an empty dictionary arg_info = inspect.getargvalues(frame) for name in arg_info.args: try: output_lines.append( " - {0:s} = {1}".format(name, repr(frame.f_locals[name])) ) except TypeError: # Happens in dict/list-comprehensions in Python 2.x name = name[0] output_lines.append( " - {0:s} = {1}".format(name, repr(frame.f_locals[name])) ) if arg_info.varargs: output_lines.append( " - *{0:s} = {1}".format( arg_info.varargs, frame.f_locals[arg_info.varargs] ) ) if arg_info.keywords: output_lines.append( " - **{0:s} = {1}".format( arg_info.keywords, frame.f_locals[arg_info.keywords] ) ) # Line block lines = _extract_lines(filename, frame.f_globals, line_no, 3) if lines: output_lines.append("") prefix = " " output_lines.append( "{0}{1}".format(prefix, "\n{0}".format(prefix).join(lines)) ) return "\n".join(output_lines)
python
def format_frame_info(frame): """ Formats the given stack frame to show its position in the code and part of its context :param frame: A stack frame """ # Same as in traceback.extract_stack line_no = frame.f_lineno code = frame.f_code filename = code.co_filename method_name = code.co_name linecache.checkcache(filename) try: # Try to get the type of the calling object instance = frame.f_locals["self"] method_name = "{0}::{1}".format(type(instance).__name__, method_name) except KeyError: # Not called from a bound method pass # File & line output_lines = [ ' File "{0}", line {1}, in {2}'.format(filename, line_no, method_name) ] # Arguments if frame.f_locals: # Pypy keeps f_locals as an empty dictionary arg_info = inspect.getargvalues(frame) for name in arg_info.args: try: output_lines.append( " - {0:s} = {1}".format(name, repr(frame.f_locals[name])) ) except TypeError: # Happens in dict/list-comprehensions in Python 2.x name = name[0] output_lines.append( " - {0:s} = {1}".format(name, repr(frame.f_locals[name])) ) if arg_info.varargs: output_lines.append( " - *{0:s} = {1}".format( arg_info.varargs, frame.f_locals[arg_info.varargs] ) ) if arg_info.keywords: output_lines.append( " - **{0:s} = {1}".format( arg_info.keywords, frame.f_locals[arg_info.keywords] ) ) # Line block lines = _extract_lines(filename, frame.f_globals, line_no, 3) if lines: output_lines.append("") prefix = " " output_lines.append( "{0}{1}".format(prefix, "\n{0}".format(prefix).join(lines)) ) return "\n".join(output_lines)
Formats the given stack frame to show its position in the code and part of its context :param frame: A stack frame
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L65-L130
tcalmant/ipopo
pelix/shell/report.py
_extract_lines
def _extract_lines(filename, f_globals, line_no, around): """ Extracts a block of lines from the given file :param filename: Name of the source file :param f_globals: Globals of the frame of the current code :param line_no: Current line of code :param around: Number of line to print before and after the current one """ current_line = linecache.getline(filename, line_no, f_globals) if not current_line: # No data on this line return "" lines = [] # Add some lines before for pre_line_no in range(line_no - around, line_no): pre_line = linecache.getline(filename, pre_line_no, f_globals) lines.append("{0}".format(pre_line.rstrip())) # The line itself lines.append("{0}".format(current_line.rstrip())) # Add some lines after for pre_line_no in range(line_no + 1, line_no + around + 1): pre_line = linecache.getline(filename, pre_line_no, f_globals) lines.append("{0}".format(pre_line.rstrip())) # Smart left strip minimal_tab = None for line in lines: if line.strip(): tab = len(line) - len(line.lstrip()) if minimal_tab is None or tab < minimal_tab: minimal_tab = tab if minimal_tab > 0: lines = [line[minimal_tab:] for line in lines] # Add some place for a marker marked_line = ">> {0}".format(lines[around]) lines = [" {0}".format(line) for line in lines] lines[around] = marked_line lines.append("") return lines
python
def _extract_lines(filename, f_globals, line_no, around): """ Extracts a block of lines from the given file :param filename: Name of the source file :param f_globals: Globals of the frame of the current code :param line_no: Current line of code :param around: Number of line to print before and after the current one """ current_line = linecache.getline(filename, line_no, f_globals) if not current_line: # No data on this line return "" lines = [] # Add some lines before for pre_line_no in range(line_no - around, line_no): pre_line = linecache.getline(filename, pre_line_no, f_globals) lines.append("{0}".format(pre_line.rstrip())) # The line itself lines.append("{0}".format(current_line.rstrip())) # Add some lines after for pre_line_no in range(line_no + 1, line_no + around + 1): pre_line = linecache.getline(filename, pre_line_no, f_globals) lines.append("{0}".format(pre_line.rstrip())) # Smart left strip minimal_tab = None for line in lines: if line.strip(): tab = len(line) - len(line.lstrip()) if minimal_tab is None or tab < minimal_tab: minimal_tab = tab if minimal_tab > 0: lines = [line[minimal_tab:] for line in lines] # Add some place for a marker marked_line = ">> {0}".format(lines[around]) lines = [" {0}".format(line) for line in lines] lines[around] = marked_line lines.append("") return lines
Extracts a block of lines from the given file :param filename: Name of the source file :param f_globals: Globals of the frame of the current code :param line_no: Current line of code :param around: Number of line to print before and after the current one
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L133-L177
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.get_methods
def get_methods(self): """ Retrieves the list of tuples (command, method) for this command handler """ return [ ("levels", self.print_levels), ("make", self.make_report), ("clear", self.clear_report), ("show", self.show_report), ("write", self.write_report), ]
python
def get_methods(self): """ Retrieves the list of tuples (command, method) for this command handler """ return [ ("levels", self.print_levels), ("make", self.make_report), ("clear", self.clear_report), ("show", self.show_report), ("write", self.write_report), ]
Retrieves the list of tuples (command, method) for this command handler
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L251-L261
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.get_level_methods
def get_level_methods(self, level): """ Returns the methods to call for the given level of report :param level: The level of report :return: The set of methods to call to fill the report :raise KeyError: Unknown level or alias """ try: # Real name of the level return set(self.__levels[level]) except KeyError: # Alias result = set() for sub_level in self.__aliases[level]: result.update(self.get_level_methods(sub_level)) return result
python
def get_level_methods(self, level): """ Returns the methods to call for the given level of report :param level: The level of report :return: The set of methods to call to fill the report :raise KeyError: Unknown level or alias """ try: # Real name of the level return set(self.__levels[level]) except KeyError: # Alias result = set() for sub_level in self.__aliases[level]: result.update(self.get_level_methods(sub_level)) return result
Returns the methods to call for the given level of report :param level: The level of report :return: The set of methods to call to fill the report :raise KeyError: Unknown level or alias
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L263-L279
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.print_levels
def print_levels(self, session): """ Lists available levels """ lines = [] for level in sorted(self.get_levels()): methods = sorted( method.__name__ for method in self.get_level_methods(level) ) lines.append("- {0}:".format(level)) lines.append("\t{0}".format(", ".join(methods))) session.write_line("\n".join(lines))
python
def print_levels(self, session): """ Lists available levels """ lines = [] for level in sorted(self.get_levels()): methods = sorted( method.__name__ for method in self.get_level_methods(level) ) lines.append("- {0}:".format(level)) lines.append("\t{0}".format(", ".join(methods))) session.write_line("\n".join(lines))
Lists available levels
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L293-L304
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.os_details
def os_details(): """ Returns a dictionary containing details about the operating system """ # Compute architecture and linkage bits, linkage = platform.architecture() results = { # Machine details "platform.arch.bits": bits, "platform.arch.linkage": linkage, "platform.machine": platform.machine(), "platform.process": platform.processor(), "sys.byteorder": sys.byteorder, # OS details "os.name": os.name, "host.name": socket.gethostname(), "sys.platform": sys.platform, "platform.system": platform.system(), "platform.release": platform.release(), "platform.version": platform.version(), "encoding.filesystem": sys.getfilesystemencoding(), } # Paths and line separators for name in "sep", "altsep", "pathsep", "linesep": results["os.{0}".format(name)] = getattr(os, name, None) try: # Available since Python 3.4 results["os.cpu_count"] = os.cpu_count() except AttributeError: results["os.cpu_count"] = None try: # Only for Unix # pylint: disable=E1101 results["sys.dlopenflags"] = sys.getdlopenflags() except AttributeError: results["sys.dlopenflags"] = None return results
python
def os_details(): """ Returns a dictionary containing details about the operating system """ # Compute architecture and linkage bits, linkage = platform.architecture() results = { # Machine details "platform.arch.bits": bits, "platform.arch.linkage": linkage, "platform.machine": platform.machine(), "platform.process": platform.processor(), "sys.byteorder": sys.byteorder, # OS details "os.name": os.name, "host.name": socket.gethostname(), "sys.platform": sys.platform, "platform.system": platform.system(), "platform.release": platform.release(), "platform.version": platform.version(), "encoding.filesystem": sys.getfilesystemencoding(), } # Paths and line separators for name in "sep", "altsep", "pathsep", "linesep": results["os.{0}".format(name)] = getattr(os, name, None) try: # Available since Python 3.4 results["os.cpu_count"] = os.cpu_count() except AttributeError: results["os.cpu_count"] = None try: # Only for Unix # pylint: disable=E1101 results["sys.dlopenflags"] = sys.getdlopenflags() except AttributeError: results["sys.dlopenflags"] = None return results
Returns a dictionary containing details about the operating system
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L307-L347
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.process_details
def process_details(): """ Returns details about the current process """ results = {"argv": sys.argv, "working.directory": os.getcwd()} # Process ID and execution IDs (UID, GID, Login, ...) for key, method in { "pid": "getpid", "ppid": "getppid", "login": "getlogin", "uid": "getuid", "euid": "geteuid", "gid": "getgid", "egid": "getegid", "groups": "getgroups", }.items(): try: results[key] = getattr(os, method)() except (AttributeError, OSError): results[key] = None return results
python
def process_details(): """ Returns details about the current process """ results = {"argv": sys.argv, "working.directory": os.getcwd()} # Process ID and execution IDs (UID, GID, Login, ...) for key, method in { "pid": "getpid", "ppid": "getppid", "login": "getlogin", "uid": "getuid", "euid": "geteuid", "gid": "getgid", "egid": "getegid", "groups": "getgroups", }.items(): try: results[key] = getattr(os, method)() except (AttributeError, OSError): results[key] = None return results
Returns details about the current process
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L357-L378
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.network_details
def network_details(): """ Returns details about the network links """ # Get IPv4 details ipv4_addresses = [ info[4][0] for info in socket.getaddrinfo( socket.gethostname(), None, socket.AF_INET ) ] # Add localhost ipv4_addresses.extend( info[4][0] for info in socket.getaddrinfo("localhost", None, socket.AF_INET) ) # Filter addresses ipv4_addresses = sorted(set(ipv4_addresses)) try: # Get IPv6 details ipv6_addresses = [ info[4][0] for info in socket.getaddrinfo( socket.gethostname(), None, socket.AF_INET6 ) ] # Add localhost ipv6_addresses.extend( info[4][0] for info in socket.getaddrinfo( "localhost", None, socket.AF_INET6 ) ) # Filter addresses ipv6_addresses = sorted(set(ipv6_addresses)) except (socket.gaierror, AttributeError): # AttributeError: AF_INET6 is missing in some versions of Python ipv6_addresses = None return { "IPv4": ipv4_addresses, "IPv6": ipv6_addresses, "host.name": socket.gethostname(), "host.fqdn": socket.getfqdn(), }
python
def network_details(): """ Returns details about the network links """ # Get IPv4 details ipv4_addresses = [ info[4][0] for info in socket.getaddrinfo( socket.gethostname(), None, socket.AF_INET ) ] # Add localhost ipv4_addresses.extend( info[4][0] for info in socket.getaddrinfo("localhost", None, socket.AF_INET) ) # Filter addresses ipv4_addresses = sorted(set(ipv4_addresses)) try: # Get IPv6 details ipv6_addresses = [ info[4][0] for info in socket.getaddrinfo( socket.gethostname(), None, socket.AF_INET6 ) ] # Add localhost ipv6_addresses.extend( info[4][0] for info in socket.getaddrinfo( "localhost", None, socket.AF_INET6 ) ) # Filter addresses ipv6_addresses = sorted(set(ipv6_addresses)) except (socket.gaierror, AttributeError): # AttributeError: AF_INET6 is missing in some versions of Python ipv6_addresses = None return { "IPv4": ipv4_addresses, "IPv6": ipv6_addresses, "host.name": socket.gethostname(), "host.fqdn": socket.getfqdn(), }
Returns details about the network links
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L381-L430
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.python_details
def python_details(): """ Returns a dictionary containing details about the Python interpreter """ build_no, build_date = platform.python_build() results = { # Version of interpreter "build.number": build_no, "build.date": build_date, "compiler": platform.python_compiler(), "branch": platform.python_branch(), "revision": platform.python_revision(), "implementation": platform.python_implementation(), "version": ".".join(str(v) for v in sys.version_info), # API version "api.version": sys.api_version, # Installation details "prefix": sys.prefix, "base_prefix": getattr(sys, "base_prefix", None), "exec_prefix": sys.exec_prefix, "base_exec_prefix": getattr(sys, "base_exec_prefix", None), # Execution details "executable": sys.executable, "encoding.default": sys.getdefaultencoding(), # Other details, ... "recursion_limit": sys.getrecursionlimit(), } # Threads implementation details thread_info = getattr(sys, "thread_info", (None, None, None)) results["thread_info.name"] = thread_info[0] results["thread_info.lock"] = thread_info[1] results["thread_info.version"] = thread_info[2] # ABI flags (POSIX only) results["abiflags"] = getattr(sys, "abiflags", None) # -X options (CPython only) results["x_options"] = getattr(sys, "_xoptions", None) return results
python
def python_details(): """ Returns a dictionary containing details about the Python interpreter """ build_no, build_date = platform.python_build() results = { # Version of interpreter "build.number": build_no, "build.date": build_date, "compiler": platform.python_compiler(), "branch": platform.python_branch(), "revision": platform.python_revision(), "implementation": platform.python_implementation(), "version": ".".join(str(v) for v in sys.version_info), # API version "api.version": sys.api_version, # Installation details "prefix": sys.prefix, "base_prefix": getattr(sys, "base_prefix", None), "exec_prefix": sys.exec_prefix, "base_exec_prefix": getattr(sys, "base_exec_prefix", None), # Execution details "executable": sys.executable, "encoding.default": sys.getdefaultencoding(), # Other details, ... "recursion_limit": sys.getrecursionlimit(), } # Threads implementation details thread_info = getattr(sys, "thread_info", (None, None, None)) results["thread_info.name"] = thread_info[0] results["thread_info.lock"] = thread_info[1] results["thread_info.version"] = thread_info[2] # ABI flags (POSIX only) results["abiflags"] = getattr(sys, "abiflags", None) # -X options (CPython only) results["x_options"] = getattr(sys, "_xoptions", None) return results
Returns a dictionary containing details about the Python interpreter
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L433-L472
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.python_modules
def python_modules(): """ Returns the list of Python modules and their file """ imported = {} results = {"builtins": sys.builtin_module_names, "imported": imported} for module_name, module_ in sys.modules.items(): if module_name not in sys.builtin_module_names: try: imported[module_name] = inspect.getfile(module_) except TypeError: imported[ module_name ] = "<no file information :: {0}>".format(repr(module_)) return results
python
def python_modules(): """ Returns the list of Python modules and their file """ imported = {} results = {"builtins": sys.builtin_module_names, "imported": imported} for module_name, module_ in sys.modules.items(): if module_name not in sys.builtin_module_names: try: imported[module_name] = inspect.getfile(module_) except TypeError: imported[ module_name ] = "<no file information :: {0}>".format(repr(module_)) return results
Returns the list of Python modules and their file
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L486-L501
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.pelix_infos
def pelix_infos(self): """ Basic information about the Pelix framework instance """ framework = self.__context.get_framework() return { "version": framework.get_version(), "properties": framework.get_properties(), }
python
def pelix_infos(self): """ Basic information about the Pelix framework instance """ framework = self.__context.get_framework() return { "version": framework.get_version(), "properties": framework.get_properties(), }
Basic information about the Pelix framework instance
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L503-L511
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.pelix_bundles
def pelix_bundles(self): """ List of installed bundles """ framework = self.__context.get_framework() return { bundle.get_bundle_id(): { "name": bundle.get_symbolic_name(), "version": bundle.get_version(), "state": bundle.get_state(), "location": bundle.get_location(), } for bundle in framework.get_bundles() }
python
def pelix_bundles(self): """ List of installed bundles """ framework = self.__context.get_framework() return { bundle.get_bundle_id(): { "name": bundle.get_symbolic_name(), "version": bundle.get_version(), "state": bundle.get_state(), "location": bundle.get_location(), } for bundle in framework.get_bundles() }
List of installed bundles
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L513-L526
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.pelix_services
def pelix_services(self): """ List of registered services """ return { svc_ref.get_property(pelix.constants.SERVICE_ID): { "specifications": svc_ref.get_property( pelix.constants.OBJECTCLASS ), "ranking": svc_ref.get_property( pelix.constants.SERVICE_RANKING ), "properties": svc_ref.get_properties(), "bundle.id": svc_ref.get_bundle().get_bundle_id(), "bundle.name": svc_ref.get_bundle().get_symbolic_name(), } for svc_ref in self.__context.get_all_service_references(None) }
python
def pelix_services(self): """ List of registered services """ return { svc_ref.get_property(pelix.constants.SERVICE_ID): { "specifications": svc_ref.get_property( pelix.constants.OBJECTCLASS ), "ranking": svc_ref.get_property( pelix.constants.SERVICE_RANKING ), "properties": svc_ref.get_properties(), "bundle.id": svc_ref.get_bundle().get_bundle_id(), "bundle.name": svc_ref.get_bundle().get_symbolic_name(), } for svc_ref in self.__context.get_all_service_references(None) }
List of registered services
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L528-L545
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.ipopo_factories
def ipopo_factories(self): """ List of iPOPO factories """ try: with use_ipopo(self.__context) as ipopo: return { name: ipopo.get_factory_details(name) for name in ipopo.get_factories() } except BundleException: # iPOPO is not available: return None
python
def ipopo_factories(self): """ List of iPOPO factories """ try: with use_ipopo(self.__context) as ipopo: return { name: ipopo.get_factory_details(name) for name in ipopo.get_factories() } except BundleException: # iPOPO is not available: return None
List of iPOPO factories
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L547-L559
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.ipopo_instances
def ipopo_instances(self): """ List of iPOPO instances """ try: with use_ipopo(self.__context) as ipopo: return { instance[0]: ipopo.get_instance_details(instance[0]) for instance in ipopo.get_instances() } except BundleException: # iPOPO is not available: return None
python
def ipopo_instances(self): """ List of iPOPO instances """ try: with use_ipopo(self.__context) as ipopo: return { instance[0]: ipopo.get_instance_details(instance[0]) for instance in ipopo.get_instances() } except BundleException: # iPOPO is not available: return None
List of iPOPO instances
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L561-L573
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.threads_list
def threads_list(): """ Lists the active threads and their current code line """ results = {} # pylint: disable=W0212 try: # Extract frames frames = sys._current_frames() # Get the thread ID -> Thread mapping names = threading._active.copy() except AttributeError: # Extraction not available return results # Sort by thread ID thread_ids = sorted(frames.keys()) for thread_id in thread_ids: # Get the corresponding stack stack = frames[thread_id] # Try to get the thread name try: name = names[thread_id].name except KeyError: name = "<unknown>" trace_lines = [] frame = stack while frame is not None: # Store the line information trace_lines.append(format_frame_info(frame)) # Previous frame... frame = frame.f_back # Construct the thread description results[thread_id] = { "name": name, "stacktrace": "\n".join(reversed(trace_lines)), } return results
python
def threads_list(): """ Lists the active threads and their current code line """ results = {} # pylint: disable=W0212 try: # Extract frames frames = sys._current_frames() # Get the thread ID -> Thread mapping names = threading._active.copy() except AttributeError: # Extraction not available return results # Sort by thread ID thread_ids = sorted(frames.keys()) for thread_id in thread_ids: # Get the corresponding stack stack = frames[thread_id] # Try to get the thread name try: name = names[thread_id].name except KeyError: name = "<unknown>" trace_lines = [] frame = stack while frame is not None: # Store the line information trace_lines.append(format_frame_info(frame)) # Previous frame... frame = frame.f_back # Construct the thread description results[thread_id] = { "name": name, "stacktrace": "\n".join(reversed(trace_lines)), } return results
Lists the active threads and their current code line
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L576-L620
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.make_report
def make_report(self, session, *levels): """ Prepares the report at the requested level(s) """ if not levels: levels = ["full"] try: # List the methods to call, avoiding double-calls methods = set() for level in levels: methods.update(self.get_level_methods(level)) except KeyError as ex: # Unknown level session.write_line("Unknown report level: {0}", ex) self.__report = None else: # Call each method self.__report = {method.__name__: method() for method in methods} # Describe the report self.__report["report"] = { "report.levels": levels, "time.stamp": time.time(), "time.local": str(datetime.datetime.now()), "time.utc": str(datetime.datetime.utcnow()), } return self.__report
python
def make_report(self, session, *levels): """ Prepares the report at the requested level(s) """ if not levels: levels = ["full"] try: # List the methods to call, avoiding double-calls methods = set() for level in levels: methods.update(self.get_level_methods(level)) except KeyError as ex: # Unknown level session.write_line("Unknown report level: {0}", ex) self.__report = None else: # Call each method self.__report = {method.__name__: method() for method in methods} # Describe the report self.__report["report"] = { "report.levels": levels, "time.stamp": time.time(), "time.local": str(datetime.datetime.now()), "time.utc": str(datetime.datetime.utcnow()), } return self.__report
Prepares the report at the requested level(s)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L622-L649
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.to_json
def to_json(self, data): """ Converts the given object to a pretty-formatted JSON string :param data: the object to convert to JSON :return: A pretty-formatted JSON string """ # Don't forget the empty line at the end of the file return ( json.dumps( data, sort_keys=True, indent=4, separators=(",", ": "), default=self.json_converter, ) + "\n" )
python
def to_json(self, data): """ Converts the given object to a pretty-formatted JSON string :param data: the object to convert to JSON :return: A pretty-formatted JSON string """ # Don't forget the empty line at the end of the file return ( json.dumps( data, sort_keys=True, indent=4, separators=(",", ": "), default=self.json_converter, ) + "\n" )
Converts the given object to a pretty-formatted JSON string :param data: the object to convert to JSON :return: A pretty-formatted JSON string
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L665-L682
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.show_report
def show_report(self, session, *levels): """ Shows the report that has been generated """ if levels: self.make_report(session, *levels) if self.__report: session.write_line(self.to_json(self.__report)) else: session.write_line("No report to show")
python
def show_report(self, session, *levels): """ Shows the report that has been generated """ if levels: self.make_report(session, *levels) if self.__report: session.write_line(self.to_json(self.__report)) else: session.write_line("No report to show")
Shows the report that has been generated
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L684-L694
tcalmant/ipopo
pelix/shell/report.py
_ReportCommands.write_report
def write_report(self, session, filename): """ Writes the report in JSON format to the given file """ if not self.__report: session.write_line("No report to write down") return try: with open(filename, "w+") as out_file: out_file.write(self.to_json(self.__report)) except IOError as ex: session.write_line("Error writing to file: {0}", ex)
python
def write_report(self, session, filename): """ Writes the report in JSON format to the given file """ if not self.__report: session.write_line("No report to write down") return try: with open(filename, "w+") as out_file: out_file.write(self.to_json(self.__report)) except IOError as ex: session.write_line("Error writing to file: {0}", ex)
Writes the report in JSON format to the given file
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/report.py#L696-L708
tcalmant/ipopo
pelix/remote/transport/mqtt_rpc.py
_MqttCallableProxy.handle_result
def handle_result(self, result, error): """ The result has been received :param result: Call result :param error: Error message """ if not self._error and not self._result: # Store results, if not already set self._error = error self._result = result # Unlock the call self._event.set()
python
def handle_result(self, result, error): """ The result has been received :param result: Call result :param error: Error message """ if not self._error and not self._result: # Store results, if not already set self._error = error self._result = result # Unlock the call self._event.set()
The result has been received :param result: Call result :param error: Error message
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/transport/mqtt_rpc.py#L301-L314
tcalmant/ipopo
samples/hooks/hook_provider.py
EventListenerHookImpl.event
def event(self, service_event, listener_dict): """ A service has been received: this method can alter the list of listeners to be notified of this event (remove only). It can also be used as a handler for the event that will be called before any standard one. :param service_event: The ServiceEvent being triggered :param listener_dict: A dictionary associating a bundle context to a list of listeners """ print( "EventListenerHookImpl: service_event=", service_event, ", listener_dict=", listener_dict, sep="", ) # Remove it if it's our service context, has the "to_filter" property # and it's the 3rd time through the hook svc_ref = service_event.get_service_reference() to_filter = svc_ref.get_property("to_filter") if self._context in listener_dict and to_filter: if self._count >= 3: print( "EventListenerHookSample removing our service listener " "so it will not be notified" ) listener_dict.pop(self._context) else: self._count += 1
python
def event(self, service_event, listener_dict): """ A service has been received: this method can alter the list of listeners to be notified of this event (remove only). It can also be used as a handler for the event that will be called before any standard one. :param service_event: The ServiceEvent being triggered :param listener_dict: A dictionary associating a bundle context to a list of listeners """ print( "EventListenerHookImpl: service_event=", service_event, ", listener_dict=", listener_dict, sep="", ) # Remove it if it's our service context, has the "to_filter" property # and it's the 3rd time through the hook svc_ref = service_event.get_service_reference() to_filter = svc_ref.get_property("to_filter") if self._context in listener_dict and to_filter: if self._count >= 3: print( "EventListenerHookSample removing our service listener " "so it will not be notified" ) listener_dict.pop(self._context) else: self._count += 1
A service has been received: this method can alter the list of listeners to be notified of this event (remove only). It can also be used as a handler for the event that will be called before any standard one. :param service_event: The ServiceEvent being triggered :param listener_dict: A dictionary associating a bundle context to a list of listeners
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/hooks/hook_provider.py#L63-L94
tcalmant/ipopo
docs/_static/tutorials/spell_checker/main_pelix_launcher.py
main
def main(): """ Starts a Pelix framework and waits for it to stop """ # Prepare the framework, with iPOPO and the shell console # Warning: we only use the first argument of this method, a list of bundles framework = pelix.framework.create_framework(( # iPOPO "pelix.ipopo.core", # Shell core (engine) "pelix.shell.core", # Text console "pelix.shell.console")) # Start the framework, and the pre-installed bundles framework.start() # Get the bundle context of the framework, i.e. the link between the # framework starter and its content. context = framework.get_bundle_context() # Start the spell dictionary bundles, which provide the dictionary services context.install_bundle("spell_dictionary_EN").start() context.install_bundle("spell_dictionary_FR").start() # Start the spell checker bundle, which provides the spell checker service. context.install_bundle("spell_checker").start() # Sample usage of the spell checker service # 1. get its service reference, that describes the service itself ref_config = context.get_service_reference("spell_checker_service") # 2. the use_service method allows to grab a service and to use it inside a # with block. It automatically releases the service when exiting the block, # even if an exception was raised with use_service(context, ref_config) as svc_config: # Here, svc_config points to the spell checker service passage = "Welcome to our framwork iPOPO" print("1. Testing Spell Checker:", passage) misspelled_words = svc_config.check(passage) print("> Misspelled_words are:", misspelled_words) # Start the spell client bundle, which provides a shell command context.install_bundle("spell_client").start() # Wait for the framework to stop framework.wait_for_stop()
python
def main(): """ Starts a Pelix framework and waits for it to stop """ # Prepare the framework, with iPOPO and the shell console # Warning: we only use the first argument of this method, a list of bundles framework = pelix.framework.create_framework(( # iPOPO "pelix.ipopo.core", # Shell core (engine) "pelix.shell.core", # Text console "pelix.shell.console")) # Start the framework, and the pre-installed bundles framework.start() # Get the bundle context of the framework, i.e. the link between the # framework starter and its content. context = framework.get_bundle_context() # Start the spell dictionary bundles, which provide the dictionary services context.install_bundle("spell_dictionary_EN").start() context.install_bundle("spell_dictionary_FR").start() # Start the spell checker bundle, which provides the spell checker service. context.install_bundle("spell_checker").start() # Sample usage of the spell checker service # 1. get its service reference, that describes the service itself ref_config = context.get_service_reference("spell_checker_service") # 2. the use_service method allows to grab a service and to use it inside a # with block. It automatically releases the service when exiting the block, # even if an exception was raised with use_service(context, ref_config) as svc_config: # Here, svc_config points to the spell checker service passage = "Welcome to our framwork iPOPO" print("1. Testing Spell Checker:", passage) misspelled_words = svc_config.check(passage) print("> Misspelled_words are:", misspelled_words) # Start the spell client bundle, which provides a shell command context.install_bundle("spell_client").start() # Wait for the framework to stop framework.wait_for_stop()
Starts a Pelix framework and waits for it to stop
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/docs/_static/tutorials/spell_checker/main_pelix_launcher.py#L15-L61
tcalmant/ipopo
pelix/misc/ssl_wrap.py
wrap_socket
def wrap_socket(socket, certfile, keyfile, password=None): """ Wraps an existing TCP socket and returns an SSLSocket object :param socket: The socket to wrap :param certfile: The server certificate file :param keyfile: The server private key file :param password: Password for the private key file (Python >= 3.3) :return: The wrapped socket :raise SSLError: Error wrapping the socket / loading the certificate :raise OSError: A password has been given, but ciphered key files are not supported by the current version of Python """ # Log warnings when some logger = logging.getLogger("ssl_wrap") def _password_support_error(): """ Logs a warning and raises an OSError if a password has been given but Python doesn't support ciphered key files. :raise OSError: If a password has been given """ if password: logger.error( "The ssl.wrap_socket() fallback method doesn't " "support key files with a password." ) raise OSError( "Can't decode the SSL key file: " "this version of Python doesn't support it" ) try: # Prefer the default context factory, as it will be updated to reflect # security issues (Python >= 2.7.9 and >= 3.4) default_context = ssl.create_default_context() except AttributeError: default_context = None try: # Try to equivalent to create_default_context() in Python 3.5 # Create an SSL context and set its options context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) if default_context is not None: # Copy options context.options = default_context.options else: # Set up the context as create_default_context() does in Python 3.5 # SSLv2 considered harmful # SSLv3 has problematic security context.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 # disallow ciphers with known vulnerabilities context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) try: # Load the certificate, with a password context.load_cert_chain(certfile, keyfile, password) except TypeError: # The "password" argument isn't supported # Check support for key file password _password_support_error() # Load the certificate, without the password argument context.load_cert_chain(certfile, keyfile) # Return the wrapped socket return context.wrap_socket(socket, server_side=True) except AttributeError as ex: # Log a warning to advise the user of possible security holes logger.warning( "Can't create a custom SSLContext. " "The server should be considered insecure." ) logger.debug("Missing attribute: %s", ex) # Check support for key file password _password_support_error() # Fall back to the "old" wrap_socket method return ssl.wrap_socket( socket, server_side=True, certfile=certfile, keyfile=keyfile )
python
def wrap_socket(socket, certfile, keyfile, password=None): """ Wraps an existing TCP socket and returns an SSLSocket object :param socket: The socket to wrap :param certfile: The server certificate file :param keyfile: The server private key file :param password: Password for the private key file (Python >= 3.3) :return: The wrapped socket :raise SSLError: Error wrapping the socket / loading the certificate :raise OSError: A password has been given, but ciphered key files are not supported by the current version of Python """ # Log warnings when some logger = logging.getLogger("ssl_wrap") def _password_support_error(): """ Logs a warning and raises an OSError if a password has been given but Python doesn't support ciphered key files. :raise OSError: If a password has been given """ if password: logger.error( "The ssl.wrap_socket() fallback method doesn't " "support key files with a password." ) raise OSError( "Can't decode the SSL key file: " "this version of Python doesn't support it" ) try: # Prefer the default context factory, as it will be updated to reflect # security issues (Python >= 2.7.9 and >= 3.4) default_context = ssl.create_default_context() except AttributeError: default_context = None try: # Try to equivalent to create_default_context() in Python 3.5 # Create an SSL context and set its options context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) if default_context is not None: # Copy options context.options = default_context.options else: # Set up the context as create_default_context() does in Python 3.5 # SSLv2 considered harmful # SSLv3 has problematic security context.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 # disallow ciphers with known vulnerabilities context.set_ciphers(_RESTRICTED_SERVER_CIPHERS) try: # Load the certificate, with a password context.load_cert_chain(certfile, keyfile, password) except TypeError: # The "password" argument isn't supported # Check support for key file password _password_support_error() # Load the certificate, without the password argument context.load_cert_chain(certfile, keyfile) # Return the wrapped socket return context.wrap_socket(socket, server_side=True) except AttributeError as ex: # Log a warning to advise the user of possible security holes logger.warning( "Can't create a custom SSLContext. " "The server should be considered insecure." ) logger.debug("Missing attribute: %s", ex) # Check support for key file password _password_support_error() # Fall back to the "old" wrap_socket method return ssl.wrap_socket( socket, server_side=True, certfile=certfile, keyfile=keyfile )
Wraps an existing TCP socket and returns an SSLSocket object :param socket: The socket to wrap :param certfile: The server certificate file :param keyfile: The server private key file :param password: Password for the private key file (Python >= 3.3) :return: The wrapped socket :raise SSLError: Error wrapping the socket / loading the certificate :raise OSError: A password has been given, but ciphered key files are not supported by the current version of Python
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/ssl_wrap.py#L54-L139
tcalmant/ipopo
pelix/http/__init__.py
make_html_list
def make_html_list(items, tag="ul"): # type: (Iterable[Any], str) -> str """ Makes a HTML list from the given iterable :param items: The items to list :param tag: The tag to use (ul or ol) :return: The HTML list code """ html_list = "\n".join( '<li><a href="{0}">{0}</a></li>'.format(item) for item in items ) return "<{0}>\n{1}\n</{0}>".format(tag, html_list)
python
def make_html_list(items, tag="ul"): # type: (Iterable[Any], str) -> str """ Makes a HTML list from the given iterable :param items: The items to list :param tag: The tag to use (ul or ol) :return: The HTML list code """ html_list = "\n".join( '<li><a href="{0}">{0}</a></li>'.format(item) for item in items ) return "<{0}>\n{1}\n</{0}>".format(tag, html_list)
Makes a HTML list from the given iterable :param items: The items to list :param tag: The tag to use (ul or ol) :return: The HTML list code
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/__init__.py#L132-L144
tcalmant/ipopo
pelix/http/__init__.py
AbstractHTTPServletRequest.read_data
def read_data(self): # type: () -> ByteString """ Reads all the data in the input stream :return: The read data """ try: size = int(self.get_header("content-length")) except (ValueError, TypeError): size = -1 return self.get_rfile().read(size)
python
def read_data(self): # type: () -> ByteString """ Reads all the data in the input stream :return: The read data """ try: size = int(self.get_header("content-length")) except (ValueError, TypeError): size = -1 return self.get_rfile().read(size)
Reads all the data in the input stream :return: The read data
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/__init__.py#L243-L255
tcalmant/ipopo
pelix/http/__init__.py
AbstractHTTPServletResponse.send_content
def send_content( self, http_code, content, mime_type="text/html", http_message=None, content_length=-1, ): # type: (int, str, str, str, int) -> None """ Utility method to send the given content as an answer. You can still use get_wfile or write afterwards, if you forced the content length. If content_length is negative (default), it will be computed as the length of the content; if it is positive, the given value will be used; if it is None, the content-length header won't be sent. :param http_code: HTTP result code :param content: Data to be sent (must be a string) :param mime_type: Content MIME type (content-type) :param http_message: HTTP code description :param content_length: Forced content length """ self.set_response(http_code, http_message) if mime_type and not self.is_header_set("content-type"): self.set_header("content-type", mime_type) # Convert the content raw_content = to_bytes(content) if content_length is not None and not self.is_header_set( "content-length" ): if content_length < 0: # Compute the length content_length = len(raw_content) # Send the length self.set_header("content-length", content_length) self.end_headers() # Send the content self.write(raw_content)
python
def send_content( self, http_code, content, mime_type="text/html", http_message=None, content_length=-1, ): # type: (int, str, str, str, int) -> None """ Utility method to send the given content as an answer. You can still use get_wfile or write afterwards, if you forced the content length. If content_length is negative (default), it will be computed as the length of the content; if it is positive, the given value will be used; if it is None, the content-length header won't be sent. :param http_code: HTTP result code :param content: Data to be sent (must be a string) :param mime_type: Content MIME type (content-type) :param http_message: HTTP code description :param content_length: Forced content length """ self.set_response(http_code, http_message) if mime_type and not self.is_header_set("content-type"): self.set_header("content-type", mime_type) # Convert the content raw_content = to_bytes(content) if content_length is not None and not self.is_header_set( "content-length" ): if content_length < 0: # Compute the length content_length = len(raw_content) # Send the length self.set_header("content-length", content_length) self.end_headers() # Send the content self.write(raw_content)
Utility method to send the given content as an answer. You can still use get_wfile or write afterwards, if you forced the content length. If content_length is negative (default), it will be computed as the length of the content; if it is positive, the given value will be used; if it is None, the content-length header won't be sent. :param http_code: HTTP result code :param content: Data to be sent (must be a string) :param mime_type: Content MIME type (content-type) :param http_message: HTTP code description :param content_length: Forced content length
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/__init__.py#L335-L380
tcalmant/ipopo
pelix/remote/discovery/multicast.py
make_mreq
def make_mreq(family, address): """ Makes a mreq structure object for the given address and socket family. :param family: A socket family (AF_INET or AF_INET6) :param address: A multicast address (group) :raise ValueError: Invalid family or address """ if not address: raise ValueError("Empty address") # Convert the address to a binary form group_bin = pton(family, address) if family == socket.AF_INET: # IPv4 # struct ip_mreq # { # struct in_addr imr_multiaddr; /* IP multicast address of group */ # struct in_addr imr_interface; /* local IP address of interface */ # }; # "=I" : Native order, standard size unsigned int return group_bin + struct.pack("=I", socket.INADDR_ANY) elif family == socket.AF_INET6: # IPv6 # struct ipv6_mreq { # struct in6_addr ipv6mr_multiaddr; # unsigned int ipv6mr_interface; # }; # "@I" : Native order, native size unsigned int return group_bin + struct.pack("@I", 0) raise ValueError("Unknown family {0}".format(family))
python
def make_mreq(family, address): """ Makes a mreq structure object for the given address and socket family. :param family: A socket family (AF_INET or AF_INET6) :param address: A multicast address (group) :raise ValueError: Invalid family or address """ if not address: raise ValueError("Empty address") # Convert the address to a binary form group_bin = pton(family, address) if family == socket.AF_INET: # IPv4 # struct ip_mreq # { # struct in_addr imr_multiaddr; /* IP multicast address of group */ # struct in_addr imr_interface; /* local IP address of interface */ # }; # "=I" : Native order, standard size unsigned int return group_bin + struct.pack("=I", socket.INADDR_ANY) elif family == socket.AF_INET6: # IPv6 # struct ipv6_mreq { # struct in6_addr ipv6mr_multiaddr; # unsigned int ipv6mr_interface; # }; # "@I" : Native order, native size unsigned int return group_bin + struct.pack("@I", 0) raise ValueError("Unknown family {0}".format(family))
Makes a mreq structure object for the given address and socket family. :param family: A socket family (AF_INET or AF_INET6) :param address: A multicast address (group) :raise ValueError: Invalid family or address
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/multicast.py#L151-L184
tcalmant/ipopo
pelix/remote/discovery/multicast.py
create_multicast_socket
def create_multicast_socket(address, port): """ Creates a multicast socket according to the given address and port. Handles both IPv4 and IPv6 addresses. :param address: Multicast address/group :param port: Socket port :return: A tuple (socket, listening address) :raise ValueError: Invalid address or port """ # Get the information about a datagram (UDP) socket, of any family try: addrs_info = socket.getaddrinfo( address, port, socket.AF_UNSPEC, socket.SOCK_DGRAM ) except socket.gaierror: raise ValueError( "Error retrieving address informations ({0}, {1})".format( address, port ) ) if len(addrs_info) > 1: _logger.debug( "More than one address information found. Using the first one." ) # Get the first entry : (family, socktype, proto, canonname, sockaddr) addr_info = addrs_info[0] # Only accept IPv4/v6 addresses if addr_info[0] not in (socket.AF_INET, socket.AF_INET6): # Unhandled address family raise ValueError("Unhandled socket family : %d" % (addr_info[0])) # Prepare the socket sock = socket.socket(addr_info[0], socket.SOCK_DGRAM, socket.IPPROTO_UDP) # Reuse address sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, "SO_REUSEPORT"): # Special for MacOS # pylint: disable=E1101 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Bind the socket if sock.family == socket.AF_INET: # IPv4 binding sock.bind(("0.0.0.0", port)) else: # IPv6 Binding sock.bind(("::", port)) # Prepare the mreq structure to join the group # addrinfo[4] = (addr,port) mreq = make_mreq(sock.family, addr_info[4][0]) # Join the group if sock.family == socket.AF_INET: # IPv4 sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # Allow multicast packets to get back on this host sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) elif sock.family == socket.AF_INET6: # IPv6 sock.setsockopt(ipproto_ipv6(), socket.IPV6_JOIN_GROUP, mreq) # Allow multicast packets to get back on this host sock.setsockopt(ipproto_ipv6(), socket.IPV6_MULTICAST_LOOP, 1) return sock, addr_info[4][0]
python
def create_multicast_socket(address, port): """ Creates a multicast socket according to the given address and port. Handles both IPv4 and IPv6 addresses. :param address: Multicast address/group :param port: Socket port :return: A tuple (socket, listening address) :raise ValueError: Invalid address or port """ # Get the information about a datagram (UDP) socket, of any family try: addrs_info = socket.getaddrinfo( address, port, socket.AF_UNSPEC, socket.SOCK_DGRAM ) except socket.gaierror: raise ValueError( "Error retrieving address informations ({0}, {1})".format( address, port ) ) if len(addrs_info) > 1: _logger.debug( "More than one address information found. Using the first one." ) # Get the first entry : (family, socktype, proto, canonname, sockaddr) addr_info = addrs_info[0] # Only accept IPv4/v6 addresses if addr_info[0] not in (socket.AF_INET, socket.AF_INET6): # Unhandled address family raise ValueError("Unhandled socket family : %d" % (addr_info[0])) # Prepare the socket sock = socket.socket(addr_info[0], socket.SOCK_DGRAM, socket.IPPROTO_UDP) # Reuse address sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, "SO_REUSEPORT"): # Special for MacOS # pylint: disable=E1101 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Bind the socket if sock.family == socket.AF_INET: # IPv4 binding sock.bind(("0.0.0.0", port)) else: # IPv6 Binding sock.bind(("::", port)) # Prepare the mreq structure to join the group # addrinfo[4] = (addr,port) mreq = make_mreq(sock.family, addr_info[4][0]) # Join the group if sock.family == socket.AF_INET: # IPv4 sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # Allow multicast packets to get back on this host sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) elif sock.family == socket.AF_INET6: # IPv6 sock.setsockopt(ipproto_ipv6(), socket.IPV6_JOIN_GROUP, mreq) # Allow multicast packets to get back on this host sock.setsockopt(ipproto_ipv6(), socket.IPV6_MULTICAST_LOOP, 1) return sock, addr_info[4][0]
Creates a multicast socket according to the given address and port. Handles both IPv4 and IPv6 addresses. :param address: Multicast address/group :param port: Socket port :return: A tuple (socket, listening address) :raise ValueError: Invalid address or port
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/multicast.py#L190-L263
tcalmant/ipopo
pelix/remote/discovery/multicast.py
close_multicast_socket
def close_multicast_socket(sock, address): """ Cleans up the given multicast socket. Unregisters it of the multicast group. Parameters should be the result of create_multicast_socket :param sock: A multicast socket :param address: The multicast address used by the socket """ if sock is None: return if address: # Prepare the mreq structure to join the group mreq = make_mreq(sock.family, address) # Quit group if sock.family == socket.AF_INET: # IPv4 sock.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, mreq) elif sock.family == socket.AF_INET6: # IPv6 sock.setsockopt(ipproto_ipv6(), socket.IPV6_LEAVE_GROUP, mreq) # Close the socket sock.close()
python
def close_multicast_socket(sock, address): """ Cleans up the given multicast socket. Unregisters it of the multicast group. Parameters should be the result of create_multicast_socket :param sock: A multicast socket :param address: The multicast address used by the socket """ if sock is None: return if address: # Prepare the mreq structure to join the group mreq = make_mreq(sock.family, address) # Quit group if sock.family == socket.AF_INET: # IPv4 sock.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, mreq) elif sock.family == socket.AF_INET6: # IPv6 sock.setsockopt(ipproto_ipv6(), socket.IPV6_LEAVE_GROUP, mreq) # Close the socket sock.close()
Cleans up the given multicast socket. Unregisters it of the multicast group. Parameters should be the result of create_multicast_socket :param sock: A multicast socket :param address: The multicast address used by the socket
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/discovery/multicast.py#L266-L293
tcalmant/ipopo
samples/rsa/helloimpl.py
HelloImpl.sayHello
def sayHello(self, name="Not given", message="nothing"): """ Synchronous implementation of IHello.sayHello synchronous method. The remote calling thread will be blocked until this is executed and responds. """ print( "Python.sayHello called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonSync says: Howdy {0} " "that's a nice runtime you got there".format(name) )
python
def sayHello(self, name="Not given", message="nothing"): """ Synchronous implementation of IHello.sayHello synchronous method. The remote calling thread will be blocked until this is executed and responds. """ print( "Python.sayHello called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonSync says: Howdy {0} " "that's a nice runtime you got there".format(name) )
Synchronous implementation of IHello.sayHello synchronous method. The remote calling thread will be blocked until this is executed and responds.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/rsa/helloimpl.py#L25-L38
tcalmant/ipopo
samples/rsa/helloimpl.py
HelloImpl.sayHelloAsync
def sayHelloAsync(self, name="Not given", message="nothing"): """ Implementation of IHello.sayHelloAsync. This method will be executed via some thread, and the remote caller will not block. This method should return either a String result (since the return type of IHello.sayHelloAsync is CompletableFuture<String>, OR a Future that returns a python string. In this case, it returns the string directly. """ print( "Python.sayHelloAsync called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonAsync says: Howdy {0} " "that's a nice runtime you got there".format(name) )
python
def sayHelloAsync(self, name="Not given", message="nothing"): """ Implementation of IHello.sayHelloAsync. This method will be executed via some thread, and the remote caller will not block. This method should return either a String result (since the return type of IHello.sayHelloAsync is CompletableFuture<String>, OR a Future that returns a python string. In this case, it returns the string directly. """ print( "Python.sayHelloAsync called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonAsync says: Howdy {0} " "that's a nice runtime you got there".format(name) )
Implementation of IHello.sayHelloAsync. This method will be executed via some thread, and the remote caller will not block. This method should return either a String result (since the return type of IHello.sayHelloAsync is CompletableFuture<String>, OR a Future that returns a python string. In this case, it returns the string directly.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/rsa/helloimpl.py#L40-L56
tcalmant/ipopo
samples/rsa/helloimpl.py
HelloImpl.sayHelloPromise
def sayHelloPromise(self, name="Not given", message="nothing"): """ Implementation of IHello.sayHelloPromise. This method will be executed via some thread, and the remote caller will not block. """ print( "Python.sayHelloPromise called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonPromise says: Howdy {0} " "that's a nice runtime you got there".format(name) )
python
def sayHelloPromise(self, name="Not given", message="nothing"): """ Implementation of IHello.sayHelloPromise. This method will be executed via some thread, and the remote caller will not block. """ print( "Python.sayHelloPromise called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonPromise says: Howdy {0} " "that's a nice runtime you got there".format(name) )
Implementation of IHello.sayHelloPromise. This method will be executed via some thread, and the remote caller will not block.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/rsa/helloimpl.py#L58-L71
tcalmant/ipopo
pelix/ipopo/core.py
_set_factory_context
def _set_factory_context(factory_class, bundle_context): # type: (type, Optional[BundleContext]) -> Optional[FactoryContext] """ Transforms the context data dictionary into its FactoryContext object form. :param factory_class: A manipulated class :param bundle_context: The class bundle context :return: The factory context, None on error """ try: # Try to get the factory context (built using decorators) context = getattr(factory_class, constants.IPOPO_FACTORY_CONTEXT) except AttributeError: # The class has not been manipulated, or too badly return None if not context.completed: # Partial context (class not manipulated) return None # Associate the factory to the bundle context context.set_bundle_context(bundle_context) return context
python
def _set_factory_context(factory_class, bundle_context): # type: (type, Optional[BundleContext]) -> Optional[FactoryContext] """ Transforms the context data dictionary into its FactoryContext object form. :param factory_class: A manipulated class :param bundle_context: The class bundle context :return: The factory context, None on error """ try: # Try to get the factory context (built using decorators) context = getattr(factory_class, constants.IPOPO_FACTORY_CONTEXT) except AttributeError: # The class has not been manipulated, or too badly return None if not context.completed: # Partial context (class not manipulated) return None # Associate the factory to the bundle context context.set_bundle_context(bundle_context) return context
Transforms the context data dictionary into its FactoryContext object form. :param factory_class: A manipulated class :param bundle_context: The class bundle context :return: The factory context, None on error
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L85-L107
tcalmant/ipopo
pelix/ipopo/core.py
_load_bundle_factories
def _load_bundle_factories(bundle): # type: (Bundle) -> List[Tuple[FactoryContext, type]] """ Retrieves a list of pairs (FactoryContext, factory class) with all readable manipulated classes found in the bundle. :param bundle: A Bundle object :return: The list of factories loaded from the bundle """ result = [] # Get the Python module module_ = bundle.get_module() # Get the bundle context bundle_context = bundle.get_bundle_context() for name in dir(module_): try: # Get the module member factory_class = getattr(module_, name) if not inspect.isclass(factory_class): continue # Check if it is a class if sys.modules[factory_class.__module__] is not module_: # Only keep classes from this module continue except (AttributeError, KeyError): # getattr() didn't work or __module__ is not a member of the class, # or the module is not known by the interpreter continue context = _set_factory_context(factory_class, bundle_context) if context is None: # Error setting up the factory context continue result.append((context, factory_class)) return result
python
def _load_bundle_factories(bundle): # type: (Bundle) -> List[Tuple[FactoryContext, type]] """ Retrieves a list of pairs (FactoryContext, factory class) with all readable manipulated classes found in the bundle. :param bundle: A Bundle object :return: The list of factories loaded from the bundle """ result = [] # Get the Python module module_ = bundle.get_module() # Get the bundle context bundle_context = bundle.get_bundle_context() for name in dir(module_): try: # Get the module member factory_class = getattr(module_, name) if not inspect.isclass(factory_class): continue # Check if it is a class if sys.modules[factory_class.__module__] is not module_: # Only keep classes from this module continue except (AttributeError, KeyError): # getattr() didn't work or __module__ is not a member of the class, # or the module is not known by the interpreter continue context = _set_factory_context(factory_class, bundle_context) if context is None: # Error setting up the factory context continue result.append((context, factory_class)) return result
Retrieves a list of pairs (FactoryContext, factory class) with all readable manipulated classes found in the bundle. :param bundle: A Bundle object :return: The list of factories loaded from the bundle
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L110-L150
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.__find_handler_factories
def __find_handler_factories(self): """ Finds all registered handler factories and stores them """ # Get the references svc_refs = self.__context.get_all_service_references( handlers_const.SERVICE_IPOPO_HANDLER_FACTORY ) if svc_refs: for svc_ref in svc_refs: # Store each handler factory self.__add_handler_factory(svc_ref)
python
def __find_handler_factories(self): """ Finds all registered handler factories and stores them """ # Get the references svc_refs = self.__context.get_all_service_references( handlers_const.SERVICE_IPOPO_HANDLER_FACTORY ) if svc_refs: for svc_ref in svc_refs: # Store each handler factory self.__add_handler_factory(svc_ref)
Finds all registered handler factories and stores them
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L206-L217
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.__add_handler_factory
def __add_handler_factory(self, svc_ref): # type: (ServiceReference) -> None """ Stores a new handler factory :param svc_ref: ServiceReference of the new handler factory """ with self.__handlers_lock: # Get the handler ID handler_id = svc_ref.get_property(handlers_const.PROP_HANDLER_ID) if handler_id in self._handlers: # Duplicated ID _logger.warning("Already registered handler ID: %s", handler_id) else: # Store the service self._handlers_refs.add(svc_ref) self._handlers[handler_id] = self.__context.get_service(svc_ref) # Try to instantiate waiting components succeeded = set() for ( name, (context, instance), ) in self.__waiting_handlers.items(): if self.__try_instantiate(context, instance): succeeded.add(name) # Remove instantiated component from the waiting list for name in succeeded: del self.__waiting_handlers[name]
python
def __add_handler_factory(self, svc_ref): # type: (ServiceReference) -> None """ Stores a new handler factory :param svc_ref: ServiceReference of the new handler factory """ with self.__handlers_lock: # Get the handler ID handler_id = svc_ref.get_property(handlers_const.PROP_HANDLER_ID) if handler_id in self._handlers: # Duplicated ID _logger.warning("Already registered handler ID: %s", handler_id) else: # Store the service self._handlers_refs.add(svc_ref) self._handlers[handler_id] = self.__context.get_service(svc_ref) # Try to instantiate waiting components succeeded = set() for ( name, (context, instance), ) in self.__waiting_handlers.items(): if self.__try_instantiate(context, instance): succeeded.add(name) # Remove instantiated component from the waiting list for name in succeeded: del self.__waiting_handlers[name]
Stores a new handler factory :param svc_ref: ServiceReference of the new handler factory
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L219-L248