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/framework.py
BundleContext.get_bundle
def get_bundle(self, bundle_id=None): # type: (Union[Bundle, int]) -> Bundle """ Retrieves the :class:`~pelix.framework.Bundle` object for the bundle matching the given ID (int). If no ID is given (None), the bundle associated to this context is returned. :param bundle_id: A bundle ID (optional) :return: The requested :class:`~pelix.framework.Bundle` object :raise BundleException: The given ID doesn't exist or is invalid """ if bundle_id is None: # Current bundle return self.__bundle elif isinstance(bundle_id, Bundle): # Got a bundle (compatibility with older install_bundle()) bundle_id = bundle_id.get_bundle_id() return self.__framework.get_bundle_by_id(bundle_id)
python
def get_bundle(self, bundle_id=None): # type: (Union[Bundle, int]) -> Bundle """ Retrieves the :class:`~pelix.framework.Bundle` object for the bundle matching the given ID (int). If no ID is given (None), the bundle associated to this context is returned. :param bundle_id: A bundle ID (optional) :return: The requested :class:`~pelix.framework.Bundle` object :raise BundleException: The given ID doesn't exist or is invalid """ if bundle_id is None: # Current bundle return self.__bundle elif isinstance(bundle_id, Bundle): # Got a bundle (compatibility with older install_bundle()) bundle_id = bundle_id.get_bundle_id() return self.__framework.get_bundle_by_id(bundle_id)
Retrieves the :class:`~pelix.framework.Bundle` object for the bundle matching the given ID (int). If no ID is given (None), the bundle associated to this context is returned. :param bundle_id: A bundle ID (optional) :return: The requested :class:`~pelix.framework.Bundle` object :raise BundleException: The given ID doesn't exist or is invalid
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1551-L1569
tcalmant/ipopo
pelix/framework.py
BundleContext.get_service_reference
def get_service_reference(self, clazz, ldap_filter=None): # type: (Optional[str], Optional[str]) -> Optional[ServiceReference] """ Returns a ServiceReference object for a service that implements and was registered under the specified class :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: A service reference, None if not found """ result = self.__framework.find_service_references( clazz, ldap_filter, True ) try: return result[0] except TypeError: return None
python
def get_service_reference(self, clazz, ldap_filter=None): # type: (Optional[str], Optional[str]) -> Optional[ServiceReference] """ Returns a ServiceReference object for a service that implements and was registered under the specified class :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: A service reference, None if not found """ result = self.__framework.find_service_references( clazz, ldap_filter, True ) try: return result[0] except TypeError: return None
Returns a ServiceReference object for a service that implements and was registered under the specified class :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: A service reference, None if not found
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1621-L1637
tcalmant/ipopo
pelix/framework.py
BundleContext.get_service_references
def get_service_references(self, clazz, ldap_filter=None): # type: (Optional[str], Optional[str]) -> Optional[List[ServiceReference]] """ Returns the service references for services that were registered under the specified class by this bundle and matching the given filter :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: The list of references to the services registered by the calling bundle and matching the filters. """ refs = self.__framework.find_service_references(clazz, ldap_filter) if refs: for ref in refs: if ref.get_bundle() is not self.__bundle: refs.remove(ref) return refs
python
def get_service_references(self, clazz, ldap_filter=None): # type: (Optional[str], Optional[str]) -> Optional[List[ServiceReference]] """ Returns the service references for services that were registered under the specified class by this bundle and matching the given filter :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: The list of references to the services registered by the calling bundle and matching the filters. """ refs = self.__framework.find_service_references(clazz, ldap_filter) if refs: for ref in refs: if ref.get_bundle() is not self.__bundle: refs.remove(ref) return refs
Returns the service references for services that were registered under the specified class by this bundle and matching the given filter :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: The list of references to the services registered by the calling bundle and matching the filters.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1639-L1656
tcalmant/ipopo
pelix/framework.py
BundleContext.install_package
def install_package(self, path, recursive=False): # type: (str, bool) -> tuple """ Installs all the modules found in the given package (directory). It is a utility method working like :meth:`~pelix.framework.BundleContext.install_visiting`, with a visitor accepting every module found. :param path: Path of the package (folder) :param recursive: If True, installs the modules found in sub-directories :return: A 2-tuple, with the list of installed bundles (:class:`~pelix.framework.Bundle`) and the list of the names of the modules which import failed. :raise ValueError: The given path is invalid """ return self.__framework.install_package(path, recursive)
python
def install_package(self, path, recursive=False): # type: (str, bool) -> tuple """ Installs all the modules found in the given package (directory). It is a utility method working like :meth:`~pelix.framework.BundleContext.install_visiting`, with a visitor accepting every module found. :param path: Path of the package (folder) :param recursive: If True, installs the modules found in sub-directories :return: A 2-tuple, with the list of installed bundles (:class:`~pelix.framework.Bundle`) and the list of the names of the modules which import failed. :raise ValueError: The given path is invalid """ return self.__framework.install_package(path, recursive)
Installs all the modules found in the given package (directory). It is a utility method working like :meth:`~pelix.framework.BundleContext.install_visiting`, with a visitor accepting every module found. :param path: Path of the package (folder) :param recursive: If True, installs the modules found in sub-directories :return: A 2-tuple, with the list of installed bundles (:class:`~pelix.framework.Bundle`) and the list of the names of the modules which import failed. :raise ValueError: The given path is invalid
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1686-L1701
tcalmant/ipopo
pelix/framework.py
BundleContext.register_service
def register_service( self, clazz, service, properties, send_event=True, factory=False, prototype=False, ): # type: (Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration """ Registers a service :param clazz: Class or Classes (list) implemented by this service :param service: The service instance :param properties: The services properties (dictionary) :param send_event: If not, doesn't trigger a service registered event :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: A ServiceRegistration object :raise BundleException: An error occurred while registering the service """ return self.__framework.register_service( self.__bundle, clazz, service, properties, send_event, factory, prototype, )
python
def register_service( self, clazz, service, properties, send_event=True, factory=False, prototype=False, ): # type: (Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration """ Registers a service :param clazz: Class or Classes (list) implemented by this service :param service: The service instance :param properties: The services properties (dictionary) :param send_event: If not, doesn't trigger a service registered event :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: A ServiceRegistration object :raise BundleException: An error occurred while registering the service """ return self.__framework.register_service( self.__bundle, clazz, service, properties, send_event, factory, prototype, )
Registers a service :param clazz: Class or Classes (list) implemented by this service :param service: The service instance :param properties: The services properties (dictionary) :param send_event: If not, doesn't trigger a service registered event :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: A ServiceRegistration object :raise BundleException: An error occurred while registering the service
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1723-L1754
tcalmant/ipopo
pelix/framework.py
BundleContext.unget_service
def unget_service(self, reference): # type: (ServiceReference) -> bool """ Disables a reference to the service :return: True if the bundle was using this reference, else False """ # Lose the dependency return self.__framework._registry.unget_service( self.__bundle, reference )
python
def unget_service(self, reference): # type: (ServiceReference) -> bool """ Disables a reference to the service :return: True if the bundle was using this reference, else False """ # Lose the dependency return self.__framework._registry.unget_service( self.__bundle, reference )
Disables a reference to the service :return: True if the bundle was using this reference, else False
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1784-L1794
tcalmant/ipopo
pelix/framework.py
FrameworkFactory.get_framework
def get_framework(cls, properties=None): # type: (Optional[dict]) -> Framework """ If it doesn't exist yet, creates a framework with the given properties, else returns the current framework instance. :return: A Pelix instance """ if cls.__singleton is None: # Normalize sys.path normalize_path() cls.__singleton = Framework(properties) return cls.__singleton
python
def get_framework(cls, properties=None): # type: (Optional[dict]) -> Framework """ If it doesn't exist yet, creates a framework with the given properties, else returns the current framework instance. :return: A Pelix instance """ if cls.__singleton is None: # Normalize sys.path normalize_path() cls.__singleton = Framework(properties) return cls.__singleton
If it doesn't exist yet, creates a framework with the given properties, else returns the current framework instance. :return: A Pelix instance
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1809-L1822
tcalmant/ipopo
pelix/framework.py
FrameworkFactory.delete_framework
def delete_framework(cls, framework=None): # type: (Optional[Framework]) -> bool # pylint: disable=W0212 """ Removes the framework singleton :return: True on success, else False """ if framework is None: framework = cls.__singleton if framework is cls.__singleton: # Stop the framework try: framework.stop() except: _logger.exception("Error stopping the framework") # Uninstall its bundles bundles = framework.get_bundles() for bundle in bundles: try: bundle.uninstall() except: _logger.exception( "Error uninstalling bundle %s", bundle.get_symbolic_name(), ) # Clear the event dispatcher framework._dispatcher.clear() # Clear the singleton cls.__singleton = None return True return False
python
def delete_framework(cls, framework=None): # type: (Optional[Framework]) -> bool # pylint: disable=W0212 """ Removes the framework singleton :return: True on success, else False """ if framework is None: framework = cls.__singleton if framework is cls.__singleton: # Stop the framework try: framework.stop() except: _logger.exception("Error stopping the framework") # Uninstall its bundles bundles = framework.get_bundles() for bundle in bundles: try: bundle.uninstall() except: _logger.exception( "Error uninstalling bundle %s", bundle.get_symbolic_name(), ) # Clear the event dispatcher framework._dispatcher.clear() # Clear the singleton cls.__singleton = None return True return False
Removes the framework singleton :return: True on success, else False
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1841-L1877
tcalmant/ipopo
pelix/rsa/__init__.py
get_matching_interfaces
def get_matching_interfaces(object_class, exported_intfs): # type: (List[str], Optional[List[str]]) -> Optional[List[str]] """ Returns the list of interfaces matching the export property :param object_class: The specifications of the service :param exported_intfs: The declared exported interfaces :return: The list of declared exported interfaces """ if object_class is None or exported_intfs is None: return None if isinstance(exported_intfs, str) and exported_intfs == "*": return object_class # after this exported_intfs will be list exported_intfs = get_string_plus_property_value(exported_intfs) if len(exported_intfs) == 1 and exported_intfs[0] == "*": return object_class return exported_intfs
python
def get_matching_interfaces(object_class, exported_intfs): # type: (List[str], Optional[List[str]]) -> Optional[List[str]] """ Returns the list of interfaces matching the export property :param object_class: The specifications of the service :param exported_intfs: The declared exported interfaces :return: The list of declared exported interfaces """ if object_class is None or exported_intfs is None: return None if isinstance(exported_intfs, str) and exported_intfs == "*": return object_class # after this exported_intfs will be list exported_intfs = get_string_plus_property_value(exported_intfs) if len(exported_intfs) == 1 and exported_intfs[0] == "*": return object_class return exported_intfs
Returns the list of interfaces matching the export property :param object_class: The specifications of the service :param exported_intfs: The declared exported interfaces :return: The list of declared exported interfaces
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1109-L1129
tcalmant/ipopo
pelix/rsa/__init__.py
get_prop_value
def get_prop_value(name, props, default=None): # type: (str, Dict[str, Any], Any) -> Any """ Returns the value of a property or the default one :param name: Name of a property :param props: Dictionary of properties :param default: Default value :return: The value of the property or the default one """ if not props: return default try: return props[name] except KeyError: return default
python
def get_prop_value(name, props, default=None): # type: (str, Dict[str, Any], Any) -> Any """ Returns the value of a property or the default one :param name: Name of a property :param props: Dictionary of properties :param default: Default value :return: The value of the property or the default one """ if not props: return default try: return props[name] except KeyError: return default
Returns the value of a property or the default one :param name: Name of a property :param props: Dictionary of properties :param default: Default value :return: The value of the property or the default one
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1132-L1148
tcalmant/ipopo
pelix/rsa/__init__.py
set_prop_if_null
def set_prop_if_null(name, props, if_null): # type: (str, Dict[str, Any], Any) -> None """ Updates the value of a property if the previous one was None :param name: Name of the property :param props: Dictionary of properties :param if_null: Value to insert if the previous was None """ value = get_prop_value(name, props) if value is None: props[name] = if_null
python
def set_prop_if_null(name, props, if_null): # type: (str, Dict[str, Any], Any) -> None """ Updates the value of a property if the previous one was None :param name: Name of the property :param props: Dictionary of properties :param if_null: Value to insert if the previous was None """ value = get_prop_value(name, props) if value is None: props[name] = if_null
Updates the value of a property if the previous one was None :param name: Name of the property :param props: Dictionary of properties :param if_null: Value to insert if the previous was None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1151-L1162
tcalmant/ipopo
pelix/rsa/__init__.py
get_string_plus_property_value
def get_string_plus_property_value(value): # type: (Any) -> Optional[List[str]] """ Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None """ if value: if isinstance(value, str): return [value] if isinstance(value, list): return value if isinstance(value, tuple): return list(value) return None
python
def get_string_plus_property_value(value): # type: (Any) -> Optional[List[str]] """ Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None """ if value: if isinstance(value, str): return [value] if isinstance(value, list): return value if isinstance(value, tuple): return list(value) return None
Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1165-L1181
tcalmant/ipopo
pelix/rsa/__init__.py
get_string_plus_property
def get_string_plus_property(name, props, default=None): # type: (str, Dict[str, Any], Optional[Any]) -> Any """ Returns the value of the given property or the default value :param name: A property name :param props: A dictionary of properties :param default: Value to return if the property doesn't exist :return: The property value or the default one """ val = get_string_plus_property_value(get_prop_value(name, props, default)) return default if val is None else val
python
def get_string_plus_property(name, props, default=None): # type: (str, Dict[str, Any], Optional[Any]) -> Any """ Returns the value of the given property or the default value :param name: A property name :param props: A dictionary of properties :param default: Value to return if the property doesn't exist :return: The property value or the default one """ val = get_string_plus_property_value(get_prop_value(name, props, default)) return default if val is None else val
Returns the value of the given property or the default value :param name: A property name :param props: A dictionary of properties :param default: Value to return if the property doesn't exist :return: The property value or the default one
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1211-L1222
tcalmant/ipopo
pelix/rsa/__init__.py
get_exported_interfaces
def get_exported_interfaces(svc_ref, overriding_props=None): # type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]] """ Looks for the interfaces exported by a service :param svc_ref: Service reference :param overriding_props: Properties overriding service ones :return: The list of exported interfaces """ # first check overriding_props for service.exported.interfaces exported_intfs = get_prop_value( SERVICE_EXPORTED_INTERFACES, overriding_props ) # then check svc_ref property if not exported_intfs: exported_intfs = svc_ref.get_property(SERVICE_EXPORTED_INTERFACES) if not exported_intfs: return None return get_matching_interfaces( svc_ref.get_property(constants.OBJECTCLASS), exported_intfs )
python
def get_exported_interfaces(svc_ref, overriding_props=None): # type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]] """ Looks for the interfaces exported by a service :param svc_ref: Service reference :param overriding_props: Properties overriding service ones :return: The list of exported interfaces """ # first check overriding_props for service.exported.interfaces exported_intfs = get_prop_value( SERVICE_EXPORTED_INTERFACES, overriding_props ) # then check svc_ref property if not exported_intfs: exported_intfs = svc_ref.get_property(SERVICE_EXPORTED_INTERFACES) if not exported_intfs: return None return get_matching_interfaces( svc_ref.get_property(constants.OBJECTCLASS), exported_intfs )
Looks for the interfaces exported by a service :param svc_ref: Service reference :param overriding_props: Properties overriding service ones :return: The list of exported interfaces
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1235-L1257
tcalmant/ipopo
pelix/rsa/__init__.py
validate_exported_interfaces
def validate_exported_interfaces(object_class, exported_intfs): # type: (List[str], List[str]) -> bool """ Validates that the exported interfaces are all provided by the service :param object_class: The specifications of a service :param exported_intfs: The exported specifications :return: True if the exported specifications are all provided by the service """ if ( not exported_intfs or not isinstance(exported_intfs, list) or not exported_intfs ): return False else: for exintf in exported_intfs: if exintf not in object_class: return False return True
python
def validate_exported_interfaces(object_class, exported_intfs): # type: (List[str], List[str]) -> bool """ Validates that the exported interfaces are all provided by the service :param object_class: The specifications of a service :param exported_intfs: The exported specifications :return: True if the exported specifications are all provided by the service """ if ( not exported_intfs or not isinstance(exported_intfs, list) or not exported_intfs ): return False else: for exintf in exported_intfs: if exintf not in object_class: return False return True
Validates that the exported interfaces are all provided by the service :param object_class: The specifications of a service :param exported_intfs: The exported specifications :return: True if the exported specifications are all provided by the service
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1260-L1279
tcalmant/ipopo
pelix/rsa/__init__.py
get_package_versions
def get_package_versions(intfs, props): # type: (List[str], Dict[str, Any]) -> List[Tuple[str, str]] """ Gets the package version of interfaces :param intfs: A list of interfaces :param props: A dictionary containing endpoint package versions :return: A list of tuples (package name, version) """ result = [] for intf in intfs: pkg_name = get_package_from_classname(intf) if pkg_name: key = ENDPOINT_PACKAGE_VERSION_ + pkg_name val = props.get(key, None) if val: result.append((key, val)) return result
python
def get_package_versions(intfs, props): # type: (List[str], Dict[str, Any]) -> List[Tuple[str, str]] """ Gets the package version of interfaces :param intfs: A list of interfaces :param props: A dictionary containing endpoint package versions :return: A list of tuples (package name, version) """ result = [] for intf in intfs: pkg_name = get_package_from_classname(intf) if pkg_name: key = ENDPOINT_PACKAGE_VERSION_ + pkg_name val = props.get(key, None) if val: result.append((key, val)) return result
Gets the package version of interfaces :param intfs: A list of interfaces :param props: A dictionary containing endpoint package versions :return: A list of tuples (package name, version)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1296-L1313
tcalmant/ipopo
pelix/rsa/__init__.py
get_rsa_props
def get_rsa_props( object_class, exported_cfgs, remote_intents=None, ep_svc_id=None, fw_id=None, pkg_vers=None, service_intents=None, ): """ Constructs a dictionary of RSA properties from the given arguments :param object_class: Service specifications :param exported_cfgs: Export configurations :param remote_intents: Supported remote intents :param ep_svc_id: Endpoint service ID :param fw_id: Remote Framework ID :param pkg_vers: Version number of the specification package :param service_intents: Service intents :return: A dictionary of properties """ results = {} if not object_class: raise ArgumentError( "object_class", "object_class must be an [] of Strings" ) results["objectClass"] = object_class if not exported_cfgs: raise ArgumentError( "exported_cfgs", "exported_cfgs must be an array of Strings" ) results[REMOTE_CONFIGS_SUPPORTED] = exported_cfgs results[SERVICE_IMPORTED_CONFIGS] = exported_cfgs if remote_intents: results[REMOTE_INTENTS_SUPPORTED] = remote_intents if service_intents: results[SERVICE_INTENTS] = service_intents if not ep_svc_id: ep_svc_id = get_next_rsid() results[ENDPOINT_SERVICE_ID] = ep_svc_id results[SERVICE_ID] = ep_svc_id if not fw_id: # No framework ID means an error fw_id = "endpoint-in-error" results[ENDPOINT_FRAMEWORK_UUID] = fw_id if pkg_vers: if isinstance(pkg_vers, type(tuple())): pkg_vers = [pkg_vers] for pkg_ver in pkg_vers: results[pkg_ver[0]] = pkg_ver[1] results[ENDPOINT_ID] = create_uuid() results[SERVICE_IMPORTED] = "true" return results
python
def get_rsa_props( object_class, exported_cfgs, remote_intents=None, ep_svc_id=None, fw_id=None, pkg_vers=None, service_intents=None, ): """ Constructs a dictionary of RSA properties from the given arguments :param object_class: Service specifications :param exported_cfgs: Export configurations :param remote_intents: Supported remote intents :param ep_svc_id: Endpoint service ID :param fw_id: Remote Framework ID :param pkg_vers: Version number of the specification package :param service_intents: Service intents :return: A dictionary of properties """ results = {} if not object_class: raise ArgumentError( "object_class", "object_class must be an [] of Strings" ) results["objectClass"] = object_class if not exported_cfgs: raise ArgumentError( "exported_cfgs", "exported_cfgs must be an array of Strings" ) results[REMOTE_CONFIGS_SUPPORTED] = exported_cfgs results[SERVICE_IMPORTED_CONFIGS] = exported_cfgs if remote_intents: results[REMOTE_INTENTS_SUPPORTED] = remote_intents if service_intents: results[SERVICE_INTENTS] = service_intents if not ep_svc_id: ep_svc_id = get_next_rsid() results[ENDPOINT_SERVICE_ID] = ep_svc_id results[SERVICE_ID] = ep_svc_id if not fw_id: # No framework ID means an error fw_id = "endpoint-in-error" results[ENDPOINT_FRAMEWORK_UUID] = fw_id if pkg_vers: if isinstance(pkg_vers, type(tuple())): pkg_vers = [pkg_vers] for pkg_ver in pkg_vers: results[pkg_ver[0]] = pkg_ver[1] results[ENDPOINT_ID] = create_uuid() results[SERVICE_IMPORTED] = "true" return results
Constructs a dictionary of RSA properties from the given arguments :param object_class: Service specifications :param exported_cfgs: Export configurations :param remote_intents: Supported remote intents :param ep_svc_id: Endpoint service ID :param fw_id: Remote Framework ID :param pkg_vers: Version number of the specification package :param service_intents: Service intents :return: A dictionary of properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1369-L1421
tcalmant/ipopo
pelix/rsa/__init__.py
get_ecf_props
def get_ecf_props(ep_id, ep_id_ns, rsvc_id=None, ep_ts=None): """ Prepares the ECF properties :param ep_id: Endpoint ID :param ep_id_ns: Namespace of the Endpoint ID :param rsvc_id: Remote service ID :param ep_ts: Timestamp of the endpoint :return: A dictionary of ECF properties """ results = {} if not ep_id: raise ArgumentError("ep_id", "ep_id must be a valid endpoint id") results[ECF_ENDPOINT_ID] = ep_id if not ep_id_ns: raise ArgumentError("ep_id_ns", "ep_id_ns must be a valid namespace") results[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = ep_id_ns if not rsvc_id: rsvc_id = get_next_rsid() results[ECF_RSVC_ID] = rsvc_id if not ep_ts: ep_ts = time_since_epoch() results[ECF_ENDPOINT_TIMESTAMP] = ep_ts return results
python
def get_ecf_props(ep_id, ep_id_ns, rsvc_id=None, ep_ts=None): """ Prepares the ECF properties :param ep_id: Endpoint ID :param ep_id_ns: Namespace of the Endpoint ID :param rsvc_id: Remote service ID :param ep_ts: Timestamp of the endpoint :return: A dictionary of ECF properties """ results = {} if not ep_id: raise ArgumentError("ep_id", "ep_id must be a valid endpoint id") results[ECF_ENDPOINT_ID] = ep_id if not ep_id_ns: raise ArgumentError("ep_id_ns", "ep_id_ns must be a valid namespace") results[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = ep_id_ns if not rsvc_id: rsvc_id = get_next_rsid() results[ECF_RSVC_ID] = rsvc_id if not ep_ts: ep_ts = time_since_epoch() results[ECF_ENDPOINT_TIMESTAMP] = ep_ts return results
Prepares the ECF properties :param ep_id: Endpoint ID :param ep_id_ns: Namespace of the Endpoint ID :param rsvc_id: Remote service ID :param ep_ts: Timestamp of the endpoint :return: A dictionary of ECF properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1424-L1447
tcalmant/ipopo
pelix/rsa/__init__.py
get_extra_props
def get_extra_props(props): # type: (Dict[str, Any]) -> Dict[str, Any] """ Returns the extra properties, *i.e.* non-ECF, non-RSA properties :param props: A dictionary of properties :return: A filtered dictionary """ return { key: value for key, value in props.items() if key not in ECFPROPNAMES and key not in RSA_PROP_NAMES and not key.startswith(ENDPOINT_PACKAGE_VERSION_) }
python
def get_extra_props(props): # type: (Dict[str, Any]) -> Dict[str, Any] """ Returns the extra properties, *i.e.* non-ECF, non-RSA properties :param props: A dictionary of properties :return: A filtered dictionary """ return { key: value for key, value in props.items() if key not in ECFPROPNAMES and key not in RSA_PROP_NAMES and not key.startswith(ENDPOINT_PACKAGE_VERSION_) }
Returns the extra properties, *i.e.* non-ECF, non-RSA properties :param props: A dictionary of properties :return: A filtered dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1450-L1464
tcalmant/ipopo
pelix/rsa/__init__.py
get_edef_props
def get_edef_props( object_class, exported_cfgs, ep_namespace, ep_id, ecf_ep_id, ep_rsvc_id, ep_ts, remote_intents=None, fw_id=None, pkg_ver=None, service_intents=None, ): """ Prepares the EDEF properties of an endpoint, merge of RSA and ECF properties """ osgi_props = get_rsa_props( object_class, exported_cfgs, remote_intents, ep_rsvc_id, fw_id, pkg_ver, service_intents, ) ecf_props = get_ecf_props(ecf_ep_id, ep_namespace, ep_rsvc_id, ep_ts) return merge_dicts(osgi_props, ecf_props)
python
def get_edef_props( object_class, exported_cfgs, ep_namespace, ep_id, ecf_ep_id, ep_rsvc_id, ep_ts, remote_intents=None, fw_id=None, pkg_ver=None, service_intents=None, ): """ Prepares the EDEF properties of an endpoint, merge of RSA and ECF properties """ osgi_props = get_rsa_props( object_class, exported_cfgs, remote_intents, ep_rsvc_id, fw_id, pkg_ver, service_intents, ) ecf_props = get_ecf_props(ecf_ep_id, ep_namespace, ep_rsvc_id, ep_ts) return merge_dicts(osgi_props, ecf_props)
Prepares the EDEF properties of an endpoint, merge of RSA and ECF properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1467-L1494
tcalmant/ipopo
pelix/rsa/__init__.py
get_dot_properties
def get_dot_properties(prefix, props, remove_prefix): # type: (str, Dict[str, Any], bool) -> Dict[str, Any] """ Gets the properties starting with the given prefix """ result_props = {} if props: dot_keys = [x for x in props.keys() if x.startswith(prefix + ".")] for dot_key in dot_keys: if remove_prefix: new_key = dot_key[len(prefix) + 1 :] else: new_key = dot_key result_props[new_key] = props.get(dot_key) return result_props
python
def get_dot_properties(prefix, props, remove_prefix): # type: (str, Dict[str, Any], bool) -> Dict[str, Any] """ Gets the properties starting with the given prefix """ result_props = {} if props: dot_keys = [x for x in props.keys() if x.startswith(prefix + ".")] for dot_key in dot_keys: if remove_prefix: new_key = dot_key[len(prefix) + 1 :] else: new_key = dot_key result_props[new_key] = props.get(dot_key) return result_props
Gets the properties starting with the given prefix
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1513-L1527
tcalmant/ipopo
pelix/rsa/__init__.py
copy_non_reserved
def copy_non_reserved(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] """ Copies all properties with non-reserved names from ``props`` to ``target`` :param props: A dictionary of properties :param target: Another dictionary :return: The target dictionary """ target.update( { key: value for key, value in props.items() if not is_reserved_property(key) } ) return target
python
def copy_non_reserved(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] """ Copies all properties with non-reserved names from ``props`` to ``target`` :param props: A dictionary of properties :param target: Another dictionary :return: The target dictionary """ target.update( { key: value for key, value in props.items() if not is_reserved_property(key) } ) return target
Copies all properties with non-reserved names from ``props`` to ``target`` :param props: A dictionary of properties :param target: Another dictionary :return: The target dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1563-L1579
tcalmant/ipopo
pelix/rsa/__init__.py
copy_non_ecf
def copy_non_ecf(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] """ Copies non-ECF properties from ``props`` to ``target`` :param props: An input dictionary :param target: The dictionary to copy non-ECF properties to :return: The ``target`` dictionary """ target.update( {key: value for key, value in props.items() if key not in ECFPROPNAMES} ) return target
python
def copy_non_ecf(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] """ Copies non-ECF properties from ``props`` to ``target`` :param props: An input dictionary :param target: The dictionary to copy non-ECF properties to :return: The ``target`` dictionary """ target.update( {key: value for key, value in props.items() if key not in ECFPROPNAMES} ) return target
Copies non-ECF properties from ``props`` to ``target`` :param props: An input dictionary :param target: The dictionary to copy non-ECF properties to :return: The ``target`` dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1582-L1594
tcalmant/ipopo
pelix/rsa/__init__.py
set_append
def set_append(input_set, item): # type: (set, Any) -> set """ Appends in-place the given item to the set. If the item is a list, all elements are added to the set. :param input_set: An existing set :param item: The item or list of items to add :return: The given set """ if item: if isinstance(item, (list, tuple)): input_set.update(item) else: input_set.add(item) return input_set
python
def set_append(input_set, item): # type: (set, Any) -> set """ Appends in-place the given item to the set. If the item is a list, all elements are added to the set. :param input_set: An existing set :param item: The item or list of items to add :return: The given set """ if item: if isinstance(item, (list, tuple)): input_set.update(item) else: input_set.add(item) return input_set
Appends in-place the given item to the set. If the item is a list, all elements are added to the set. :param input_set: An existing set :param item: The item or list of items to add :return: The given set
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1597-L1612
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromimportreg
def fromimportreg(cls, bundle, import_reg): # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an ImportRegistration """ exc = import_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_ERROR, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), None, None, exc, import_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_REGISTRATION, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), import_reg.get_import_reference(), None, None, import_reg.get_description(), )
python
def fromimportreg(cls, bundle, import_reg): # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an ImportRegistration """ exc = import_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_ERROR, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), None, None, exc, import_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_REGISTRATION, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), import_reg.get_import_reference(), None, None, import_reg.get_description(), )
Creates a RemoteServiceAdminEvent object from an ImportRegistration
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L769-L796
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromexportreg
def fromexportreg(cls, bundle, export_reg): # type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an ExportRegistration """ exc = export_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_ERROR, bundle, export_reg.get_export_container_id(), export_reg.get_remoteservice_id(), None, None, exc, export_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_REGISTRATION, bundle, export_reg.get_export_container_id(), export_reg.get_remoteservice_id(), None, export_reg.get_export_reference(), None, export_reg.get_description(), )
python
def fromexportreg(cls, bundle, export_reg): # type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an ExportRegistration """ exc = export_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_ERROR, bundle, export_reg.get_export_container_id(), export_reg.get_remoteservice_id(), None, None, exc, export_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_REGISTRATION, bundle, export_reg.get_export_container_id(), export_reg.get_remoteservice_id(), None, export_reg.get_export_reference(), None, export_reg.get_description(), )
Creates a RemoteServiceAdminEvent object from an ExportRegistration
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L799-L826
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromexportupdate
def fromexportupdate(cls, bundle, export_reg): # type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the update of an ExportRegistration """ exc = export_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_ERROR, bundle, export_reg.get_export_container_id(), export_reg.get_remoteservice_id(), None, export_reg.get_export_reference(), None, export_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_UPDATE, bundle, export_reg.get_export_container_id(), export_reg.get_remoteservice_id(), None, export_reg.get_export_reference(), None, export_reg.get_description(), )
python
def fromexportupdate(cls, bundle, export_reg): # type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the update of an ExportRegistration """ exc = export_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_ERROR, bundle, export_reg.get_export_container_id(), export_reg.get_remoteservice_id(), None, export_reg.get_export_reference(), None, export_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_UPDATE, bundle, export_reg.get_export_container_id(), export_reg.get_remoteservice_id(), None, export_reg.get_export_reference(), None, export_reg.get_description(), )
Creates a RemoteServiceAdminEvent object from the update of an ExportRegistration
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L829-L857
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromimportupdate
def fromimportupdate(cls, bundle, import_reg): # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the update of an ImportRegistration """ exc = import_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_ERROR, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), None, None, exc, import_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_UPDATE, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), import_reg.get_import_reference(), None, None, import_reg.get_description(), )
python
def fromimportupdate(cls, bundle, import_reg): # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the update of an ImportRegistration """ exc = import_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_ERROR, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), None, None, exc, import_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_UPDATE, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), import_reg.get_import_reference(), None, None, import_reg.get_description(), )
Creates a RemoteServiceAdminEvent object from the update of an ImportRegistration
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L860-L888
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromimportunreg
def fromimportunreg( cls, bundle, cid, rsid, import_ref, exception, endpoint ): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ImportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the departure of an ImportRegistration """ return RemoteServiceAdminEvent( typ=RemoteServiceAdminEvent.IMPORT_UNREGISTRATION, bundle=bundle, cid=cid, rsid=rsid, import_ref=import_ref, exception=exception, endpoint=endpoint, )
python
def fromimportunreg( cls, bundle, cid, rsid, import_ref, exception, endpoint ): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ImportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the departure of an ImportRegistration """ return RemoteServiceAdminEvent( typ=RemoteServiceAdminEvent.IMPORT_UNREGISTRATION, bundle=bundle, cid=cid, rsid=rsid, import_ref=import_ref, exception=exception, endpoint=endpoint, )
Creates a RemoteServiceAdminEvent object from the departure of an ImportRegistration
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L891-L907
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromexportunreg
def fromexportunreg( cls, bundle, exporterid, rsid, export_ref, exception, endpoint ): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ExportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the departure of an ExportRegistration """ return RemoteServiceAdminEvent( typ=RemoteServiceAdminEvent.EXPORT_UNREGISTRATION, bundle=bundle, cid=exporterid, rsid=rsid, export_ref=export_ref, exception=exception, endpoint=endpoint, )
python
def fromexportunreg( cls, bundle, exporterid, rsid, export_ref, exception, endpoint ): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ExportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from the departure of an ExportRegistration """ return RemoteServiceAdminEvent( typ=RemoteServiceAdminEvent.EXPORT_UNREGISTRATION, bundle=bundle, cid=exporterid, rsid=rsid, export_ref=export_ref, exception=exception, endpoint=endpoint, )
Creates a RemoteServiceAdminEvent object from the departure of an ExportRegistration
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L910-L926
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromimporterror
def fromimporterror(cls, bundle, importerid, rsid, exception, endpoint): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an import error """ return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_ERROR, bundle, importerid, rsid, None, None, exception, endpoint, )
python
def fromimporterror(cls, bundle, importerid, rsid, exception, endpoint): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an import error """ return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_ERROR, bundle, importerid, rsid, None, None, exception, endpoint, )
Creates a RemoteServiceAdminEvent object from an import error
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L929-L943
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromexporterror
def fromexporterror(cls, bundle, exporterid, rsid, exception, endpoint): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an export error """ return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_ERROR, bundle, exporterid, rsid, None, None, exception, endpoint, )
python
def fromexporterror(cls, bundle, exporterid, rsid, exception, endpoint): # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an export error """ return RemoteServiceAdminEvent( RemoteServiceAdminEvent.EXPORT_ERROR, bundle, exporterid, rsid, None, None, exception, endpoint, )
Creates a RemoteServiceAdminEvent object from an export error
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L946-L960
tcalmant/ipopo
pelix/ipopo/waiting.py
IPopoWaitingList._try_instantiate
def _try_instantiate(self, ipopo, factory, component): # type: (Any, str, str) -> None """ Tries to instantiate a component from the queue. Hides all exceptions. :param ipopo: The iPOPO service :param factory: Component factory :param component: Component name """ try: # Get component properties with self.__lock: properties = self.__queue[factory][component] except KeyError: # Component not in queue return else: try: # Try instantiation ipopo.instantiate(factory, component, properties) except TypeError: # Unknown factory: try later pass except ValueError as ex: # Already known component _logger.error("Component already running: %s", ex) except Exception as ex: # Other error _logger.exception("Error instantiating component: %s", ex)
python
def _try_instantiate(self, ipopo, factory, component): # type: (Any, str, str) -> None """ Tries to instantiate a component from the queue. Hides all exceptions. :param ipopo: The iPOPO service :param factory: Component factory :param component: Component name """ try: # Get component properties with self.__lock: properties = self.__queue[factory][component] except KeyError: # Component not in queue return else: try: # Try instantiation ipopo.instantiate(factory, component, properties) except TypeError: # Unknown factory: try later pass except ValueError as ex: # Already known component _logger.error("Component already running: %s", ex) except Exception as ex: # Other error _logger.exception("Error instantiating component: %s", ex)
Tries to instantiate a component from the queue. Hides all exceptions. :param ipopo: The iPOPO service :param factory: Component factory :param component: Component name
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L93-L121
tcalmant/ipopo
pelix/ipopo/waiting.py
IPopoWaitingList._start
def _start(self): """ Starts the instantiation queue (called by its bundle activator) """ try: # Try to register to factory events with use_ipopo(self.__context) as ipopo: ipopo.add_listener(self) except BundleException: # Service not yet present pass # Register the iPOPO service listener self.__context.add_service_listener(self, specification=SERVICE_IPOPO)
python
def _start(self): """ Starts the instantiation queue (called by its bundle activator) """ try: # Try to register to factory events with use_ipopo(self.__context) as ipopo: ipopo.add_listener(self) except BundleException: # Service not yet present pass # Register the iPOPO service listener self.__context.add_service_listener(self, specification=SERVICE_IPOPO)
Starts the instantiation queue (called by its bundle activator)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L123-L136
tcalmant/ipopo
pelix/ipopo/waiting.py
IPopoWaitingList._stop
def _stop(self): """ Stops the instantiation queue (called by its bundle activator) """ # Unregisters the iPOPO service listener self.__context.remove_service_listener(self) try: # Try to register to factory events with use_ipopo(self.__context) as ipopo: ipopo.remove_listener(self) except BundleException: # Service not present anymore pass
python
def _stop(self): """ Stops the instantiation queue (called by its bundle activator) """ # Unregisters the iPOPO service listener self.__context.remove_service_listener(self) try: # Try to register to factory events with use_ipopo(self.__context) as ipopo: ipopo.remove_listener(self) except BundleException: # Service not present anymore pass
Stops the instantiation queue (called by its bundle activator)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L138-L151
tcalmant/ipopo
pelix/ipopo/waiting.py
IPopoWaitingList._clear
def _clear(self): """ Clear all references (called by its bundle activator) """ self.__names.clear() self.__queue.clear() self.__context = None
python
def _clear(self): """ Clear all references (called by its bundle activator) """ self.__names.clear() self.__queue.clear() self.__context = None
Clear all references (called by its bundle activator)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L153-L159
tcalmant/ipopo
pelix/ipopo/waiting.py
IPopoWaitingList.service_changed
def service_changed(self, event): # type: (ServiceEvent) -> None """ Handles an event about the iPOPO service """ kind = event.get_kind() if kind == ServiceEvent.REGISTERED: # iPOPO service registered: register to factory events with use_ipopo(self.__context) as ipopo: ipopo.add_listener(self)
python
def service_changed(self, event): # type: (ServiceEvent) -> None """ Handles an event about the iPOPO service """ kind = event.get_kind() if kind == ServiceEvent.REGISTERED: # iPOPO service registered: register to factory events with use_ipopo(self.__context) as ipopo: ipopo.add_listener(self)
Handles an event about the iPOPO service
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L161-L170
tcalmant/ipopo
pelix/ipopo/waiting.py
IPopoWaitingList.handle_ipopo_event
def handle_ipopo_event(self, event): # type: (IPopoEvent) -> None """ Handles an iPOPO event :param event: iPOPO event bean """ kind = event.get_kind() if kind == IPopoEvent.REGISTERED: # A factory has been registered try: with use_ipopo(self.__context) as ipopo: factory = event.get_factory_name() with self.__lock: # Copy the list of components names for this factory components = self.__queue[factory].copy() for component in components: self._try_instantiate(ipopo, factory, component) except BundleException: # iPOPO not yet started pass except KeyError: # No components for this new factory pass
python
def handle_ipopo_event(self, event): # type: (IPopoEvent) -> None """ Handles an iPOPO event :param event: iPOPO event bean """ kind = event.get_kind() if kind == IPopoEvent.REGISTERED: # A factory has been registered try: with use_ipopo(self.__context) as ipopo: factory = event.get_factory_name() with self.__lock: # Copy the list of components names for this factory components = self.__queue[factory].copy() for component in components: self._try_instantiate(ipopo, factory, component) except BundleException: # iPOPO not yet started pass except KeyError: # No components for this new factory pass
Handles an iPOPO event :param event: iPOPO event bean
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L172-L197
tcalmant/ipopo
pelix/ipopo/waiting.py
IPopoWaitingList.add
def add(self, factory, component, properties=None): # type: (str, str, dict) -> None """ Enqueues the instantiation of the given component :param factory: Factory name :param component: Component name :param properties: Component properties :raise ValueError: Component name already reserved in the queue :raise Exception: Error instantiating the component """ with self.__lock: if component in self.__names: raise ValueError( "Component name already queued: {0}".format(component) ) # Normalize properties if properties is None: properties = {} # Store component description self.__names[component] = factory self.__queue.setdefault(factory, {})[component] = properties try: with use_ipopo(self.__context) as ipopo: # Try to instantiate the component right now self._try_instantiate(ipopo, factory, component) except BundleException: # iPOPO not yet started pass
python
def add(self, factory, component, properties=None): # type: (str, str, dict) -> None """ Enqueues the instantiation of the given component :param factory: Factory name :param component: Component name :param properties: Component properties :raise ValueError: Component name already reserved in the queue :raise Exception: Error instantiating the component """ with self.__lock: if component in self.__names: raise ValueError( "Component name already queued: {0}".format(component) ) # Normalize properties if properties is None: properties = {} # Store component description self.__names[component] = factory self.__queue.setdefault(factory, {})[component] = properties try: with use_ipopo(self.__context) as ipopo: # Try to instantiate the component right now self._try_instantiate(ipopo, factory, component) except BundleException: # iPOPO not yet started pass
Enqueues the instantiation of the given component :param factory: Factory name :param component: Component name :param properties: Component properties :raise ValueError: Component name already reserved in the queue :raise Exception: Error instantiating the component
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L199-L230
tcalmant/ipopo
pelix/ipopo/waiting.py
IPopoWaitingList.remove
def remove(self, component): # type: (str) -> None """ Kills/Removes the component with the given name :param component: A component name :raise KeyError: Unknown component """ with self.__lock: # Find its factory factory = self.__names.pop(component) components = self.__queue[factory] # Clear the queue del components[component] if not components: # No more component for this factory del self.__queue[factory] # Kill the component try: with use_ipopo(self.__context) as ipopo: # Try to instantiate the component right now ipopo.kill(component) except (BundleException, ValueError): # iPOPO not yet started or component not instantiated pass
python
def remove(self, component): # type: (str) -> None """ Kills/Removes the component with the given name :param component: A component name :raise KeyError: Unknown component """ with self.__lock: # Find its factory factory = self.__names.pop(component) components = self.__queue[factory] # Clear the queue del components[component] if not components: # No more component for this factory del self.__queue[factory] # Kill the component try: with use_ipopo(self.__context) as ipopo: # Try to instantiate the component right now ipopo.kill(component) except (BundleException, ValueError): # iPOPO not yet started or component not instantiated pass
Kills/Removes the component with the given name :param component: A component name :raise KeyError: Unknown component
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L232-L258
tcalmant/ipopo
pelix/shell/remote.py
_create_server
def _create_server( shell, server_address, port, cert_file=None, key_file=None, key_password=None, ca_file=None, ): """ Creates the TCP console on the given address and port :param shell: The remote shell handler :param server_address: Server bound address :param port: Server port :param cert_file: Path to the server certificate :param key_file: Path to the server private key :param key_password: Password for the key file :param ca_file: Path to Certificate Authority to authenticate clients :return: A tuple: Server thread, TCP server object, Server active flag """ # Set up the request handler creator active_flag = SharedBoolean(True) def request_handler(*rh_args): """ Constructs a RemoteConsole as TCP request handler """ return RemoteConsole(shell, active_flag, *rh_args) # Set up the server server = ThreadingTCPServerFamily( (server_address, port), request_handler, cert_file, key_file, key_password, ca_file, ) # Set flags server.daemon_threads = True server.allow_reuse_address = True # Activate the server server.server_bind() server.server_activate() # Serve clients server_thread = threading.Thread( target=server.serve_forever, name="RemoteShell-{0}".format(port) ) server_thread.daemon = True server_thread.start() return server_thread, server, active_flag
python
def _create_server( shell, server_address, port, cert_file=None, key_file=None, key_password=None, ca_file=None, ): """ Creates the TCP console on the given address and port :param shell: The remote shell handler :param server_address: Server bound address :param port: Server port :param cert_file: Path to the server certificate :param key_file: Path to the server private key :param key_password: Password for the key file :param ca_file: Path to Certificate Authority to authenticate clients :return: A tuple: Server thread, TCP server object, Server active flag """ # Set up the request handler creator active_flag = SharedBoolean(True) def request_handler(*rh_args): """ Constructs a RemoteConsole as TCP request handler """ return RemoteConsole(shell, active_flag, *rh_args) # Set up the server server = ThreadingTCPServerFamily( (server_address, port), request_handler, cert_file, key_file, key_password, ca_file, ) # Set flags server.daemon_threads = True server.allow_reuse_address = True # Activate the server server.server_bind() server.server_activate() # Serve clients server_thread = threading.Thread( target=server.serve_forever, name="RemoteShell-{0}".format(port) ) server_thread.daemon = True server_thread.start() return server_thread, server, active_flag
Creates the TCP console on the given address and port :param shell: The remote shell handler :param server_address: Server bound address :param port: Server port :param cert_file: Path to the server certificate :param key_file: Path to the server private key :param key_password: Password for the key file :param ca_file: Path to Certificate Authority to authenticate clients :return: A tuple: Server thread, TCP server object, Server active flag
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/remote.py#L370-L425
tcalmant/ipopo
pelix/shell/remote.py
_run_interpreter
def _run_interpreter(variables, banner): """ Runs a Python interpreter console and blocks until the user exits it. :param variables: Interpreters variables (locals) :param banner: Start-up banners """ # Script-only imports import code try: import readline import rlcompleter readline.set_completer(rlcompleter.Completer(variables).complete) readline.parse_and_bind("tab: complete") except ImportError: # readline is not available: ignore pass # Start the console shell = code.InteractiveConsole(variables) shell.interact(banner)
python
def _run_interpreter(variables, banner): """ Runs a Python interpreter console and blocks until the user exits it. :param variables: Interpreters variables (locals) :param banner: Start-up banners """ # Script-only imports import code try: import readline import rlcompleter readline.set_completer(rlcompleter.Completer(variables).complete) readline.parse_and_bind("tab: complete") except ImportError: # readline is not available: ignore pass # Start the console shell = code.InteractiveConsole(variables) shell.interact(banner)
Runs a Python interpreter console and blocks until the user exits it. :param variables: Interpreters variables (locals) :param banner: Start-up banners
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/remote.py#L565-L587
tcalmant/ipopo
pelix/shell/remote.py
main
def main(argv=None): """ Script entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None """ # Prepare arguments parser = argparse.ArgumentParser( prog="pelix.shell.remote", parents=[make_common_parser()], description="Pelix Remote Shell ({} SSL support)".format( "with" if ssl is not None else "without" ), ) # Remote shell options group = parser.add_argument_group("Remote Shell options") group.add_argument( "-a", "--address", default="localhost", help="The remote shell binding address", ) group.add_argument( "-p", "--port", type=int, default=9000, help="The remote shell binding port", ) if ssl is not None: # Remote Shell TLS options group = parser.add_argument_group("TLS Options") group.add_argument("--cert", help="Path to the server certificate file") group.add_argument( "--key", help="Path to the server key file " "(can be omitted if the key is in the certificate)", ) group.add_argument( "--key-password", help="Password of the server key." "Set to '-' for a password request.", ) group.add_argument( "--ca-chain", help="Path to the CA chain file to authenticate clients", ) # Local options group = parser.add_argument_group("Local options") group.add_argument( "--no-input", action="store_true", help="Run without input (for daemon mode)", ) # Parse them args = parser.parse_args(argv) # Handle arguments init = handle_common_arguments(args) # Set the initial bundles bundles = [ "pelix.ipopo.core", "pelix.shell.core", "pelix.shell.ipopo", "pelix.shell.remote", ] bundles.extend(init.bundles) # Start a Pelix framework framework = pelix.framework.create_framework( utilities.remove_duplicates(bundles), init.properties ) framework.start() context = framework.get_bundle_context() # Instantiate configured components init.instantiate_components(framework.get_bundle_context()) # Instantiate a Remote Shell, if necessary with use_ipopo(context) as ipopo: rshell_name = "remote-shell" try: ipopo.get_instance_details(rshell_name) except ValueError: # Component doesn't exist, we can instantiate it. if ssl is not None: # Copy parsed arguments ca_chain = args.ca_chain cert = args.cert key = args.key # Normalize the TLS key file password argument if args.key_password == "-": import getpass key_password = getpass.getpass( "Password for {}: ".format(args.key or args.cert) ) else: key_password = args.key_password else: # SSL support is missing: # Ensure the SSL arguments are defined but set to None ca_chain = None cert = None key = None key_password = None # Setup the component rshell = ipopo.instantiate( pelix.shell.FACTORY_REMOTE_SHELL, rshell_name, { "pelix.shell.address": args.address, "pelix.shell.port": args.port, "pelix.shell.ssl.ca": ca_chain, "pelix.shell.ssl.cert": cert, "pelix.shell.ssl.key": key, "pelix.shell.ssl.key_password": key_password, }, ) # Avoid loose reference to the password del key_password else: logging.error( "A remote shell component (%s) is already " "configured. Abandon.", rshell_name, ) return 1 # Prepare a banner host, port = rshell.get_access() try: if args.no_input: # No input required: just print the access to the shell print("Remote shell bound to:", host, "- port:", port) try: while not framework.wait_for_stop(1): # Awake from wait every second to let KeyboardInterrupt # exception to raise pass except KeyboardInterrupt: print("Got Ctrl+C: exiting.") return 127 else: # Prepare interpreter variables variables = { "__name__": "__console__", "__doc__": None, "__package__": None, "framework": framework, "context": context, "use_ipopo": use_ipopo, } banner = ( "{lines}\nPython interpreter with Pelix Remote Shell\n" "Remote shell bound to: {host}:{port}\n{lines}\n" "Python version: {version}\n".format( lines="-" * 80, version=sys.version, host=host, port=port ) ) # Run an interpreter _run_interpreter(variables, banner) finally: # Stop the framework framework.stop()
python
def main(argv=None): """ Script entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None """ # Prepare arguments parser = argparse.ArgumentParser( prog="pelix.shell.remote", parents=[make_common_parser()], description="Pelix Remote Shell ({} SSL support)".format( "with" if ssl is not None else "without" ), ) # Remote shell options group = parser.add_argument_group("Remote Shell options") group.add_argument( "-a", "--address", default="localhost", help="The remote shell binding address", ) group.add_argument( "-p", "--port", type=int, default=9000, help="The remote shell binding port", ) if ssl is not None: # Remote Shell TLS options group = parser.add_argument_group("TLS Options") group.add_argument("--cert", help="Path to the server certificate file") group.add_argument( "--key", help="Path to the server key file " "(can be omitted if the key is in the certificate)", ) group.add_argument( "--key-password", help="Password of the server key." "Set to '-' for a password request.", ) group.add_argument( "--ca-chain", help="Path to the CA chain file to authenticate clients", ) # Local options group = parser.add_argument_group("Local options") group.add_argument( "--no-input", action="store_true", help="Run without input (for daemon mode)", ) # Parse them args = parser.parse_args(argv) # Handle arguments init = handle_common_arguments(args) # Set the initial bundles bundles = [ "pelix.ipopo.core", "pelix.shell.core", "pelix.shell.ipopo", "pelix.shell.remote", ] bundles.extend(init.bundles) # Start a Pelix framework framework = pelix.framework.create_framework( utilities.remove_duplicates(bundles), init.properties ) framework.start() context = framework.get_bundle_context() # Instantiate configured components init.instantiate_components(framework.get_bundle_context()) # Instantiate a Remote Shell, if necessary with use_ipopo(context) as ipopo: rshell_name = "remote-shell" try: ipopo.get_instance_details(rshell_name) except ValueError: # Component doesn't exist, we can instantiate it. if ssl is not None: # Copy parsed arguments ca_chain = args.ca_chain cert = args.cert key = args.key # Normalize the TLS key file password argument if args.key_password == "-": import getpass key_password = getpass.getpass( "Password for {}: ".format(args.key or args.cert) ) else: key_password = args.key_password else: # SSL support is missing: # Ensure the SSL arguments are defined but set to None ca_chain = None cert = None key = None key_password = None # Setup the component rshell = ipopo.instantiate( pelix.shell.FACTORY_REMOTE_SHELL, rshell_name, { "pelix.shell.address": args.address, "pelix.shell.port": args.port, "pelix.shell.ssl.ca": ca_chain, "pelix.shell.ssl.cert": cert, "pelix.shell.ssl.key": key, "pelix.shell.ssl.key_password": key_password, }, ) # Avoid loose reference to the password del key_password else: logging.error( "A remote shell component (%s) is already " "configured. Abandon.", rshell_name, ) return 1 # Prepare a banner host, port = rshell.get_access() try: if args.no_input: # No input required: just print the access to the shell print("Remote shell bound to:", host, "- port:", port) try: while not framework.wait_for_stop(1): # Awake from wait every second to let KeyboardInterrupt # exception to raise pass except KeyboardInterrupt: print("Got Ctrl+C: exiting.") return 127 else: # Prepare interpreter variables variables = { "__name__": "__console__", "__doc__": None, "__package__": None, "framework": framework, "context": context, "use_ipopo": use_ipopo, } banner = ( "{lines}\nPython interpreter with Pelix Remote Shell\n" "Remote shell bound to: {host}:{port}\n{lines}\n" "Python version: {version}\n".format( lines="-" * 80, version=sys.version, host=host, port=port ) ) # Run an interpreter _run_interpreter(variables, banner) finally: # Stop the framework framework.stop()
Script entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/remote.py#L590-L767
tcalmant/ipopo
pelix/shell/remote.py
RemoteConsole.send
def send(self, data): """ Tries to send data to the client. :param data: Data to be sent :return: True if the data was sent, False on error """ if data is not None: data = data.encode("UTF-8") try: self.wfile.write(data) self.wfile.flush() return True except IOError: # An error occurred, mask it # -> This allows to handle the command even if the client has been # disconnect (i.e. "echo stop 0 | nc localhost 9000") return False
python
def send(self, data): """ Tries to send data to the client. :param data: Data to be sent :return: True if the data was sent, False on error """ if data is not None: data = data.encode("UTF-8") try: self.wfile.write(data) self.wfile.flush() return True except IOError: # An error occurred, mask it # -> This allows to handle the command even if the client has been # disconnect (i.e. "echo stop 0 | nc localhost 9000") return False
Tries to send data to the client. :param data: Data to be sent :return: True if the data was sent, False on error
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/remote.py#L138-L157
tcalmant/ipopo
pelix/shell/remote.py
RemoteConsole.handle
def handle(self): """ Handles a TCP client """ _logger.info( "RemoteConsole client connected: [%s]:%d", self.client_address[0], self.client_address[1], ) # Prepare the session session = beans.ShellSession( beans.IOHandler(self.rfile, self.wfile), {"remote_client_ip": self.client_address[0]}, ) # Print the banner def get_ps1(): """ Gets the prompt string from the session of the shell service :return: The prompt string """ try: return session.get("PS1") except KeyError: return self._shell.get_ps1() self.send(self._shell.get_banner()) self.send(get_ps1()) try: while self._active.get_value(): # Wait for data rlist = select([self.connection], [], [], .5)[0] if not rlist: # Nothing to do (poll timed out) continue data = self.rfile.readline() if not data: # End of stream (client gone) break # Strip the line line = data.strip() if not data: # Empty line continue # Execute it try: self._shell.handle_line(line, session) except KeyboardInterrupt: # Stop there on interruption self.send("\nInterruption received.") return except IOError as ex: # I/O errors are fatal _logger.exception( "Error communicating with a client: %s", ex ) break except Exception as ex: # Other exceptions are not important import traceback self.send("\nError during last command: {0}\n".format(ex)) self.send(traceback.format_exc()) # Print the prompt self.send(get_ps1()) finally: _logger.info( "RemoteConsole client gone: [%s]:%d", self.client_address[0], self.client_address[1], ) try: # Be polite self.send("\nSession closed. Good bye.\n") self.finish() except IOError as ex: _logger.warning("Error cleaning up connection: %s", ex)
python
def handle(self): """ Handles a TCP client """ _logger.info( "RemoteConsole client connected: [%s]:%d", self.client_address[0], self.client_address[1], ) # Prepare the session session = beans.ShellSession( beans.IOHandler(self.rfile, self.wfile), {"remote_client_ip": self.client_address[0]}, ) # Print the banner def get_ps1(): """ Gets the prompt string from the session of the shell service :return: The prompt string """ try: return session.get("PS1") except KeyError: return self._shell.get_ps1() self.send(self._shell.get_banner()) self.send(get_ps1()) try: while self._active.get_value(): # Wait for data rlist = select([self.connection], [], [], .5)[0] if not rlist: # Nothing to do (poll timed out) continue data = self.rfile.readline() if not data: # End of stream (client gone) break # Strip the line line = data.strip() if not data: # Empty line continue # Execute it try: self._shell.handle_line(line, session) except KeyboardInterrupt: # Stop there on interruption self.send("\nInterruption received.") return except IOError as ex: # I/O errors are fatal _logger.exception( "Error communicating with a client: %s", ex ) break except Exception as ex: # Other exceptions are not important import traceback self.send("\nError during last command: {0}\n".format(ex)) self.send(traceback.format_exc()) # Print the prompt self.send(get_ps1()) finally: _logger.info( "RemoteConsole client gone: [%s]:%d", self.client_address[0], self.client_address[1], ) try: # Be polite self.send("\nSession closed. Good bye.\n") self.finish() except IOError as ex: _logger.warning("Error cleaning up connection: %s", ex)
Handles a TCP client
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/remote.py#L159-L243
tcalmant/ipopo
pelix/shell/remote.py
ThreadingTCPServerFamily.get_request
def get_request(self): """ Accepts a new client. Sets up SSL wrapping if necessary. :return: A tuple: (client socket, client address tuple) """ # Accept the client client_socket, client_address = self.socket.accept() if ssl is not None and self.cert_file: # Setup an SSL context to accept clients with a certificate # signed by a known chain of authority. # Other clients will be rejected during handshake. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) try: # Force a valid/signed client-side certificate context.verify_mode = ssl.CERT_REQUIRED # Load the server certificate context.load_cert_chain( certfile=self.cert_file, keyfile=self.key_file, password=self.key_password, ) if self.ca_file: # Load the given authority chain context.load_verify_locations(self.ca_file) else: # Load the default chain if none given context.load_default_certs(ssl.Purpose.CLIENT_AUTH) except Exception as ex: # Explicitly log the error as the default behaviour hides it _logger.error("Error setting up the SSL context: %s", ex) raise try: # SSL handshake client_stream = context.wrap_socket( client_socket, server_side=True ) except ssl.SSLError as ex: # Explicitly log the exception before re-raising it _logger.warning( "Error during SSL handshake with %s: %s", client_address, ex ) raise else: # Nothing to do, use the raw socket client_stream = client_socket return client_stream, client_address
python
def get_request(self): """ Accepts a new client. Sets up SSL wrapping if necessary. :return: A tuple: (client socket, client address tuple) """ # Accept the client client_socket, client_address = self.socket.accept() if ssl is not None and self.cert_file: # Setup an SSL context to accept clients with a certificate # signed by a known chain of authority. # Other clients will be rejected during handshake. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) try: # Force a valid/signed client-side certificate context.verify_mode = ssl.CERT_REQUIRED # Load the server certificate context.load_cert_chain( certfile=self.cert_file, keyfile=self.key_file, password=self.key_password, ) if self.ca_file: # Load the given authority chain context.load_verify_locations(self.ca_file) else: # Load the default chain if none given context.load_default_certs(ssl.Purpose.CLIENT_AUTH) except Exception as ex: # Explicitly log the error as the default behaviour hides it _logger.error("Error setting up the SSL context: %s", ex) raise try: # SSL handshake client_stream = context.wrap_socket( client_socket, server_side=True ) except ssl.SSLError as ex: # Explicitly log the exception before re-raising it _logger.warning( "Error during SSL handshake with %s: %s", client_address, ex ) raise else: # Nothing to do, use the raw socket client_stream = client_socket return client_stream, client_address
Accepts a new client. Sets up SSL wrapping if necessary. :return: A tuple: (client socket, client address tuple)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/remote.py#L301-L352
tcalmant/ipopo
pelix/shell/remote.py
ThreadingTCPServerFamily.process_request
def process_request(self, request, client_address): """ Starts a new thread to process the request, adding the client address in its name. """ thread = threading.Thread( name="RemoteShell-{0}-Client-{1}".format( self.server_address[1], client_address[:2] ), target=self.process_request_thread, args=(request, client_address), ) thread.daemon = self.daemon_threads thread.start()
python
def process_request(self, request, client_address): """ Starts a new thread to process the request, adding the client address in its name. """ thread = threading.Thread( name="RemoteShell-{0}-Client-{1}".format( self.server_address[1], client_address[:2] ), target=self.process_request_thread, args=(request, client_address), ) thread.daemon = self.daemon_threads thread.start()
Starts a new thread to process the request, adding the client address in its name.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/remote.py#L354-L367
tcalmant/ipopo
pelix/shell/completion/ipopo.py
ComponentFactoryCompleter.display_hook
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match (-1 for the trailing space) match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1) # Sort matching names matches = sorted(match for match in matches) # Print the match and the associated name session.write_line() with use_ipopo(context) as ipopo: for factory_name in matches: # Remove the spaces added for the completion factory_name = factory_name.strip() bnd = ipopo.get_factory_bundle(factory_name) session.write_line( match_pattern, factory_name, bnd.get_symbolic_name() ) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
python
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match (-1 for the trailing space) match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1) # Sort matching names matches = sorted(match for match in matches) # Print the match and the associated name session.write_line() with use_ipopo(context) as ipopo: for factory_name in matches: # Remove the spaces added for the completion factory_name = factory_name.strip() bnd = ipopo.get_factory_bundle(factory_name) session.write_line( match_pattern, factory_name, bnd.get_symbolic_name() ) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/ipopo.py#L79-L110
tcalmant/ipopo
pelix/shell/completion/ipopo.py
ComponentFactoryCompleter.complete
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of component factories with use_ipopo(context) as ipopo: return [ "{} ".format(factory) for factory in ipopo.get_factories() if factory.startswith(current) ]
python
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of component factories with use_ipopo(context) as ipopo: return [ "{} ".format(factory) for factory in ipopo.get_factories() if factory.startswith(current) ]
Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/ipopo.py#L112-L136
tcalmant/ipopo
pelix/shell/completion/ipopo.py
ComponentInstanceCompleter.display_hook
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match (-1 for the trailing space) match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1) # Sort matching names matches = sorted(match for match in matches) # Print the match and the associated name session.write_line() with use_ipopo(context) as ipopo: for name in matches: # Remove the spaces added for the completion name = name.strip() details = ipopo.get_instance_details(name) description = "of {factory} ({state})".format(**details) session.write_line(match_pattern, name, description) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
python
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match (-1 for the trailing space) match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1) # Sort matching names matches = sorted(match for match in matches) # Print the match and the associated name session.write_line() with use_ipopo(context) as ipopo: for name in matches: # Remove the spaces added for the completion name = name.strip() details = ipopo.get_instance_details(name) description = "of {factory} ({state})".format(**details) session.write_line(match_pattern, name, description) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/ipopo.py#L145-L175
tcalmant/ipopo
pelix/shell/completion/ipopo.py
ComponentInstanceCompleter.complete
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of component factories with use_ipopo(context) as ipopo: return [ "{} ".format(name) for name, _, _ in ipopo.get_instances() if name.startswith(current) ]
python
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of component factories with use_ipopo(context) as ipopo: return [ "{} ".format(name) for name, _, _ in ipopo.get_instances() if name.startswith(current) ]
Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/ipopo.py#L177-L201
tcalmant/ipopo
pelix/shell/completion/ipopo.py
ComponentFactoryPropertiesCompleter.complete
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ with use_ipopo(context) as ipopo: try: # Find the factory name for idx, completer_id in enumerate(config.completers): if completer_id == FACTORY: factory_name = current_arguments[idx] break else: # No factory completer found in signature for idx, completer_id in enumerate(config.completers): if completer_id == COMPONENT: name = current_arguments[idx] details = ipopo.get_instance_details(name) factory_name = details["factory"] break else: # No factory name can be found return [] # Get the details about this factory details = ipopo.get_factory_details(factory_name) properties = details["properties"] except (IndexError, ValueError): # No/unknown factory name return [] else: return [ "{}=".format(key) for key in properties if key.startswith(current) ]
python
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ with use_ipopo(context) as ipopo: try: # Find the factory name for idx, completer_id in enumerate(config.completers): if completer_id == FACTORY: factory_name = current_arguments[idx] break else: # No factory completer found in signature for idx, completer_id in enumerate(config.completers): if completer_id == COMPONENT: name = current_arguments[idx] details = ipopo.get_instance_details(name) factory_name = details["factory"] break else: # No factory name can be found return [] # Get the details about this factory details = ipopo.get_factory_details(factory_name) properties = details["properties"] except (IndexError, ValueError): # No/unknown factory name return [] else: return [ "{}=".format(key) for key in properties if key.startswith(current) ]
Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/ipopo.py#L209-L254
tcalmant/ipopo
pelix/http/basic.py
_HTTPServletRequest.get_header
def get_header(self, name, default=None): """ Retrieves the value of a header """ return self._handler.headers.get(name, default)
python
def get_header(self, name, default=None): """ Retrieves the value of a header """ return self._handler.headers.get(name, default)
Retrieves the value of a header
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/basic.py#L135-L139
tcalmant/ipopo
pelix/http/basic.py
_HTTPServletResponse.end_headers
def end_headers(self): """ Ends the headers part """ # Send them all at once for name, value in self._headers.items(): self._handler.send_header(name, value) self._handler.end_headers()
python
def end_headers(self): """ Ends the headers part """ # Send them all at once for name, value in self._headers.items(): self._handler.send_header(name, value) self._handler.end_headers()
Ends the headers part
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/basic.py#L219-L227
tcalmant/ipopo
pelix/http/basic.py
_RequestHandler.log_error
def log_error(self, message, *args, **kwargs): # pylint: disable=W0221 """ Log server error """ self._service.log(logging.ERROR, message, *args, **kwargs)
python
def log_error(self, message, *args, **kwargs): # pylint: disable=W0221 """ Log server error """ self._service.log(logging.ERROR, message, *args, **kwargs)
Log server error
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/basic.py#L315-L320
tcalmant/ipopo
pelix/http/basic.py
_RequestHandler.log_request
def log_request(self, code="-", size="-"): """ Logs a request to the server """ self._service.log(logging.DEBUG, '"%s" %s', self.requestline, code)
python
def log_request(self, code="-", size="-"): """ Logs a request to the server """ self._service.log(logging.DEBUG, '"%s" %s', self.requestline, code)
Logs a request to the server
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/basic.py#L322-L326
tcalmant/ipopo
pelix/http/basic.py
_RequestHandler.send_no_servlet_response
def send_no_servlet_response(self): """ Default response sent when no servlet is found for the requested path """ # Use the helper to send the error page response = _HTTPServletResponse(self) response.send_content(404, self._service.make_not_found_page(self.path))
python
def send_no_servlet_response(self): """ Default response sent when no servlet is found for the requested path """ # Use the helper to send the error page response = _HTTPServletResponse(self) response.send_content(404, self._service.make_not_found_page(self.path))
Default response sent when no servlet is found for the requested path
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/basic.py#L328-L334
tcalmant/ipopo
pelix/http/basic.py
_RequestHandler.send_exception
def send_exception(self, response): """ Sends an exception page with a 500 error code. Must be called from inside the exception handling block. :param response: The response handler """ # Get a formatted stack trace stack = traceback.format_exc() # Log the error self.log_error( "Error handling request upon: %s\n%s\n", self.path, stack ) # Send the page response.send_content( 500, self._service.make_exception_page(self.path, stack) )
python
def send_exception(self, response): """ Sends an exception page with a 500 error code. Must be called from inside the exception handling block. :param response: The response handler """ # Get a formatted stack trace stack = traceback.format_exc() # Log the error self.log_error( "Error handling request upon: %s\n%s\n", self.path, stack ) # Send the page response.send_content( 500, self._service.make_exception_page(self.path, stack) )
Sends an exception page with a 500 error code. Must be called from inside the exception handling block. :param response: The response handler
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/basic.py#L336-L354
tcalmant/ipopo
pelix/http/basic.py
_HttpServerFamily.server_bind
def server_bind(self): """ Override server_bind to store the server name, even in IronPython. See https://ironpython.codeplex.com/workitem/29477 """ TCPServer.server_bind(self) host, port = self.socket.getsockname()[:2] self.server_port = port try: self.server_name = socket.getfqdn(host) except ValueError: # Use the local host name in case of error, like CPython does self.server_name = socket.gethostname()
python
def server_bind(self): """ Override server_bind to store the server name, even in IronPython. See https://ironpython.codeplex.com/workitem/29477 """ TCPServer.server_bind(self) host, port = self.socket.getsockname()[:2] self.server_port = port try: self.server_name = socket.getfqdn(host) except ValueError: # Use the local host name in case of error, like CPython does self.server_name = socket.gethostname()
Override server_bind to store the server name, even in IronPython. See https://ironpython.codeplex.com/workitem/29477
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/basic.py#L419-L432
tcalmant/ipopo
pelix/rsa/endpointdescription.py
encode_list
def encode_list(key, list_): # type: (str, Iterable) -> Dict[str, str] """ Converts a list into a space-separated string and puts it in a dictionary :param key: Dictionary key to store the list :param list_: A list of objects :return: A dictionary key->string or an empty dictionary """ if not list_: return {} return {key: " ".join(str(i) for i in list_)}
python
def encode_list(key, list_): # type: (str, Iterable) -> Dict[str, str] """ Converts a list into a space-separated string and puts it in a dictionary :param key: Dictionary key to store the list :param list_: A list of objects :return: A dictionary key->string or an empty dictionary """ if not list_: return {} return {key: " ".join(str(i) for i in list_)}
Converts a list into a space-separated string and puts it in a dictionary :param key: Dictionary key to store the list :param list_: A list of objects :return: A dictionary key->string or an empty dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L89-L100
tcalmant/ipopo
pelix/rsa/endpointdescription.py
package_name
def package_name(package): # type: (str) -> str """ Returns the package name of the given module name """ if not package: return "" lastdot = package.rfind(".") if lastdot == -1: return package return package[:lastdot]
python
def package_name(package): # type: (str) -> str """ Returns the package name of the given module name """ if not package: return "" lastdot = package.rfind(".") if lastdot == -1: return package return package[:lastdot]
Returns the package name of the given module name
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L103-L115
tcalmant/ipopo
pelix/rsa/endpointdescription.py
encode_osgi_props
def encode_osgi_props(ed): # type: (EndpointDescription) -> Dict[str, str] """ Prepares a dictionary of OSGi properties for the given EndpointDescription """ result_props = {} intfs = ed.get_interfaces() result_props[OBJECTCLASS] = " ".join(intfs) for intf in intfs: pkg_name = package_name(intf) ver = ed.get_package_version(pkg_name) if ver and not ver == (0, 0, 0): result_props[ENDPOINT_PACKAGE_VERSION_] = ".".join( str(v) for v in ver ) result_props[ENDPOINT_ID] = ed.get_id() result_props[ENDPOINT_SERVICE_ID] = "{0}".format(ed.get_service_id()) result_props[ENDPOINT_FRAMEWORK_UUID] = ed.get_framework_uuid() imp_configs = ed.get_imported_configs() if imp_configs: result_props[SERVICE_IMPORTED_CONFIGS] = " ".join( ed.get_imported_configs() ) intents = ed.get_intents() if intents: result_props[SERVICE_INTENTS] = " ".join(intents) remote_configs = ed.get_remote_configs_supported() if remote_configs: result_props[REMOTE_CONFIGS_SUPPORTED] = " ".join(remote_configs) remote_intents = ed.get_remote_intents_supported() if remote_intents: result_props[REMOTE_INTENTS_SUPPORTED] = " ".join(remote_intents) return result_props
python
def encode_osgi_props(ed): # type: (EndpointDescription) -> Dict[str, str] """ Prepares a dictionary of OSGi properties for the given EndpointDescription """ result_props = {} intfs = ed.get_interfaces() result_props[OBJECTCLASS] = " ".join(intfs) for intf in intfs: pkg_name = package_name(intf) ver = ed.get_package_version(pkg_name) if ver and not ver == (0, 0, 0): result_props[ENDPOINT_PACKAGE_VERSION_] = ".".join( str(v) for v in ver ) result_props[ENDPOINT_ID] = ed.get_id() result_props[ENDPOINT_SERVICE_ID] = "{0}".format(ed.get_service_id()) result_props[ENDPOINT_FRAMEWORK_UUID] = ed.get_framework_uuid() imp_configs = ed.get_imported_configs() if imp_configs: result_props[SERVICE_IMPORTED_CONFIGS] = " ".join( ed.get_imported_configs() ) intents = ed.get_intents() if intents: result_props[SERVICE_INTENTS] = " ".join(intents) remote_configs = ed.get_remote_configs_supported() if remote_configs: result_props[REMOTE_CONFIGS_SUPPORTED] = " ".join(remote_configs) remote_intents = ed.get_remote_intents_supported() if remote_intents: result_props[REMOTE_INTENTS_SUPPORTED] = " ".join(remote_intents) return result_props
Prepares a dictionary of OSGi properties for the given EndpointDescription
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L118-L151
tcalmant/ipopo
pelix/rsa/endpointdescription.py
decode_list
def decode_list(input_props, name): # type: (Dict[str, str], str) -> List[str] """ Decodes a space-separated list """ val_str = input_props.get(name, None) if val_str: return val_str.split(" ") return []
python
def decode_list(input_props, name): # type: (Dict[str, str], str) -> List[str] """ Decodes a space-separated list """ val_str = input_props.get(name, None) if val_str: return val_str.split(" ") return []
Decodes a space-separated list
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L154-L162
tcalmant/ipopo
pelix/rsa/endpointdescription.py
decode_osgi_props
def decode_osgi_props(input_props): # type: (Dict[str, Any]) -> Dict[str, Any] """ Decodes the OSGi properties of the given endpoint properties """ result_props = {} intfs = decode_list(input_props, OBJECTCLASS) result_props[OBJECTCLASS] = intfs for intf in intfs: package_key = ENDPOINT_PACKAGE_VERSION_ + package_name(intf) intfversionstr = input_props.get(package_key, None) if intfversionstr: result_props[package_key] = intfversionstr result_props[ENDPOINT_ID] = input_props[ENDPOINT_ID] result_props[ENDPOINT_SERVICE_ID] = input_props[ENDPOINT_SERVICE_ID] result_props[ENDPOINT_FRAMEWORK_UUID] = input_props[ENDPOINT_FRAMEWORK_UUID] imp_configs = decode_list(input_props, SERVICE_IMPORTED_CONFIGS) if imp_configs: result_props[SERVICE_IMPORTED_CONFIGS] = imp_configs intents = decode_list(input_props, SERVICE_INTENTS) if intents: result_props[SERVICE_INTENTS] = intents remote_configs = decode_list(input_props, REMOTE_CONFIGS_SUPPORTED) if remote_configs: result_props[REMOTE_CONFIGS_SUPPORTED] = remote_configs remote_intents = decode_list(input_props, REMOTE_INTENTS_SUPPORTED) if remote_intents: result_props[REMOTE_INTENTS_SUPPORTED] = remote_intents return result_props
python
def decode_osgi_props(input_props): # type: (Dict[str, Any]) -> Dict[str, Any] """ Decodes the OSGi properties of the given endpoint properties """ result_props = {} intfs = decode_list(input_props, OBJECTCLASS) result_props[OBJECTCLASS] = intfs for intf in intfs: package_key = ENDPOINT_PACKAGE_VERSION_ + package_name(intf) intfversionstr = input_props.get(package_key, None) if intfversionstr: result_props[package_key] = intfversionstr result_props[ENDPOINT_ID] = input_props[ENDPOINT_ID] result_props[ENDPOINT_SERVICE_ID] = input_props[ENDPOINT_SERVICE_ID] result_props[ENDPOINT_FRAMEWORK_UUID] = input_props[ENDPOINT_FRAMEWORK_UUID] imp_configs = decode_list(input_props, SERVICE_IMPORTED_CONFIGS) if imp_configs: result_props[SERVICE_IMPORTED_CONFIGS] = imp_configs intents = decode_list(input_props, SERVICE_INTENTS) if intents: result_props[SERVICE_INTENTS] = intents remote_configs = decode_list(input_props, REMOTE_CONFIGS_SUPPORTED) if remote_configs: result_props[REMOTE_CONFIGS_SUPPORTED] = remote_configs remote_intents = decode_list(input_props, REMOTE_INTENTS_SUPPORTED) if remote_intents: result_props[REMOTE_INTENTS_SUPPORTED] = remote_intents return result_props
Decodes the OSGi properties of the given endpoint properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L165-L193
tcalmant/ipopo
pelix/rsa/endpointdescription.py
decode_endpoint_props
def decode_endpoint_props(input_props): # type: (Dict) -> Dict[str, Any] """ Decodes the endpoint properties from the given dictionary """ ed_props = decode_osgi_props(input_props) ed_props[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = input_props[ ECF_ENDPOINT_CONTAINERID_NAMESPACE ] ed_props[ECF_RSVC_ID] = int(input_props[ECF_RSVC_ID]) ed_props[ECF_ENDPOINT_ID] = input_props[ECF_ENDPOINT_ID] ed_props[ECF_ENDPOINT_TIMESTAMP] = int(input_props[ECF_ENDPOINT_TIMESTAMP]) target_id = input_props.get(ECF_ENDPOINT_CONNECTTARGET_ID, None) if target_id: ed_props[ECF_ENDPOINT_CONNECTTARGET_ID] = target_id id_filters = decode_list(input_props, ECF_ENDPOINT_IDFILTER_IDS) if id_filters: ed_props[ECF_ENDPOINT_IDFILTER_IDS] = id_filters rs_filter = input_props.get(ECF_ENDPOINT_REMOTESERVICE_FILTER, None) if rs_filter: ed_props[ECF_ENDPOINT_REMOTESERVICE_FILTER] = rs_filter async_intfs = input_props.get(ECF_SERVICE_EXPORTED_ASYNC_INTERFACES, None) if async_intfs: if async_intfs == "*": ed_props[ECF_SERVICE_EXPORTED_ASYNC_INTERFACES] = async_intfs else: async_intfs = decode_list( input_props, ECF_SERVICE_EXPORTED_ASYNC_INTERFACES ) if async_intfs: ed_props[ECF_SERVICE_EXPORTED_ASYNC_INTERFACES] = async_intfs for key in input_props.keys(): if not is_reserved_property(key): val = input_props.get(key, None) if val: ed_props[key] = val return ed_props
python
def decode_endpoint_props(input_props): # type: (Dict) -> Dict[str, Any] """ Decodes the endpoint properties from the given dictionary """ ed_props = decode_osgi_props(input_props) ed_props[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = input_props[ ECF_ENDPOINT_CONTAINERID_NAMESPACE ] ed_props[ECF_RSVC_ID] = int(input_props[ECF_RSVC_ID]) ed_props[ECF_ENDPOINT_ID] = input_props[ECF_ENDPOINT_ID] ed_props[ECF_ENDPOINT_TIMESTAMP] = int(input_props[ECF_ENDPOINT_TIMESTAMP]) target_id = input_props.get(ECF_ENDPOINT_CONNECTTARGET_ID, None) if target_id: ed_props[ECF_ENDPOINT_CONNECTTARGET_ID] = target_id id_filters = decode_list(input_props, ECF_ENDPOINT_IDFILTER_IDS) if id_filters: ed_props[ECF_ENDPOINT_IDFILTER_IDS] = id_filters rs_filter = input_props.get(ECF_ENDPOINT_REMOTESERVICE_FILTER, None) if rs_filter: ed_props[ECF_ENDPOINT_REMOTESERVICE_FILTER] = rs_filter async_intfs = input_props.get(ECF_SERVICE_EXPORTED_ASYNC_INTERFACES, None) if async_intfs: if async_intfs == "*": ed_props[ECF_SERVICE_EXPORTED_ASYNC_INTERFACES] = async_intfs else: async_intfs = decode_list( input_props, ECF_SERVICE_EXPORTED_ASYNC_INTERFACES ) if async_intfs: ed_props[ECF_SERVICE_EXPORTED_ASYNC_INTERFACES] = async_intfs for key in input_props.keys(): if not is_reserved_property(key): val = input_props.get(key, None) if val: ed_props[key] = val return ed_props
Decodes the endpoint properties from the given dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L196-L233
tcalmant/ipopo
pelix/rsa/endpointdescription.py
encode_endpoint_props
def encode_endpoint_props(ed): """ Encodes the properties of the given EndpointDescription """ props = encode_osgi_props(ed) props[ECF_RSVC_ID] = "{0}".format(ed.get_remoteservice_id()[1]) props[ECF_ENDPOINT_ID] = "{0}".format(ed.get_container_id()[1]) props[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = "{0}".format( ed.get_container_id()[0] ) props[ECF_ENDPOINT_TIMESTAMP] = "{0}".format(ed.get_timestamp()) ctid = ed.get_connect_target_id() if ctid: props[ECF_ENDPOINT_CONNECTTARGET_ID] = "{0}".format(ctid) id_filters = ed.get_id_filters() if id_filters: props[ECF_ENDPOINT_IDFILTER_IDS] = " ".join([x[1] for x in id_filters]) rs_filter = ed.get_remoteservice_filter() if rs_filter: props[ECF_ENDPOINT_REMOTESERVICE_FILTER] = ed.get_remoteservice_filter() async_intfs = ed.get_async_interfaces() if async_intfs: props[ECF_SERVICE_EXPORTED_ASYNC_INTERFACES] = " ".join(async_intfs) all_props = ed.get_properties() other_props = { key: all_props[key] for key in all_props.keys() if not is_reserved_property(key) } return merge_dicts(props, other_props)
python
def encode_endpoint_props(ed): """ Encodes the properties of the given EndpointDescription """ props = encode_osgi_props(ed) props[ECF_RSVC_ID] = "{0}".format(ed.get_remoteservice_id()[1]) props[ECF_ENDPOINT_ID] = "{0}".format(ed.get_container_id()[1]) props[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = "{0}".format( ed.get_container_id()[0] ) props[ECF_ENDPOINT_TIMESTAMP] = "{0}".format(ed.get_timestamp()) ctid = ed.get_connect_target_id() if ctid: props[ECF_ENDPOINT_CONNECTTARGET_ID] = "{0}".format(ctid) id_filters = ed.get_id_filters() if id_filters: props[ECF_ENDPOINT_IDFILTER_IDS] = " ".join([x[1] for x in id_filters]) rs_filter = ed.get_remoteservice_filter() if rs_filter: props[ECF_ENDPOINT_REMOTESERVICE_FILTER] = ed.get_remoteservice_filter() async_intfs = ed.get_async_interfaces() if async_intfs: props[ECF_SERVICE_EXPORTED_ASYNC_INTERFACES] = " ".join(async_intfs) all_props = ed.get_properties() other_props = { key: all_props[key] for key in all_props.keys() if not is_reserved_property(key) } return merge_dicts(props, other_props)
Encodes the properties of the given EndpointDescription
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L236-L266
tcalmant/ipopo
pelix/rsa/endpointdescription.py
EndpointDescription.get_package_version
def get_package_version(self, package): # type: (str) -> Tuple[int, int, int] """ Provides the version of the given package name. :param package: The name of the package :return: The version of the specified package as a tuple or (0,0,0) """ name = "{0}{1}".format(ENDPOINT_PACKAGE_VERSION_, package) try: # Get the version string version = self._properties[name] # Split dots ('.') return tuple(version.split(".")) except KeyError: # No version return 0, 0, 0
python
def get_package_version(self, package): # type: (str) -> Tuple[int, int, int] """ Provides the version of the given package name. :param package: The name of the package :return: The version of the specified package as a tuple or (0,0,0) """ name = "{0}{1}".format(ENDPOINT_PACKAGE_VERSION_, package) try: # Get the version string version = self._properties[name] # Split dots ('.') return tuple(version.split(".")) except KeyError: # No version return 0, 0, 0
Provides the version of the given package name. :param package: The name of the package :return: The version of the specified package as a tuple or (0,0,0)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L555-L571
tcalmant/ipopo
pelix/rsa/endpointdescription.py
EndpointDescription.is_same_service
def is_same_service(self, endpoint): # type: (EndpointDescription) -> bool """ Tests if this endpoint and the given one have the same framework UUID and service ID :param endpoint: Another endpoint :return: True if both endpoints represent the same remote service """ return ( self.get_framework_uuid() == endpoint.get_framework_uuid() and self.get_service_id() == endpoint.get_service_id() )
python
def is_same_service(self, endpoint): # type: (EndpointDescription) -> bool """ Tests if this endpoint and the given one have the same framework UUID and service ID :param endpoint: Another endpoint :return: True if both endpoints represent the same remote service """ return ( self.get_framework_uuid() == endpoint.get_framework_uuid() and self.get_service_id() == endpoint.get_service_id() )
Tests if this endpoint and the given one have the same framework UUID and service ID :param endpoint: Another endpoint :return: True if both endpoints represent the same remote service
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/endpointdescription.py#L582-L594
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.generate_id
def generate_id(cls, prefix="pelix-"): """ Generates a random MQTT client ID :param prefix: Client ID prefix (truncated to 8 chars) :return: A client ID of 22 or 23 characters """ if not prefix: # Normalize string prefix = "" else: # Truncate long prefixes prefix = prefix[:8] # Prepare the missing part nb_bytes = (23 - len(prefix)) // 2 random_bytes = os.urandom(nb_bytes) if sys.version_info[0] >= 3: random_ints = [char for char in random_bytes] else: random_ints = [ord(char) for char in random_bytes] random_id = "".join("{0:02x}".format(value) for value in random_ints) return "{0}{1}".format(prefix, random_id)
python
def generate_id(cls, prefix="pelix-"): """ Generates a random MQTT client ID :param prefix: Client ID prefix (truncated to 8 chars) :return: A client ID of 22 or 23 characters """ if not prefix: # Normalize string prefix = "" else: # Truncate long prefixes prefix = prefix[:8] # Prepare the missing part nb_bytes = (23 - len(prefix)) // 2 random_bytes = os.urandom(nb_bytes) if sys.version_info[0] >= 3: random_ints = [char for char in random_bytes] else: random_ints = [ord(char) for char in random_bytes] random_id = "".join("{0:02x}".format(value) for value in random_ints) return "{0}{1}".format(prefix, random_id)
Generates a random MQTT client ID :param prefix: Client ID prefix (truncated to 8 chars) :return: A client ID of 22 or 23 characters
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L141-L165
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.set_will
def set_will(self, topic, payload, qos=0, retain=False): """ Sets up the will message :param topic: Topic of the will message :param payload: Content of the message :param qos: Quality of Service :param retain: The message will be retained :raise ValueError: Invalid topic :raise TypeError: Invalid payload """ self.__mqtt.will_set(topic, payload, qos, retain=retain)
python
def set_will(self, topic, payload, qos=0, retain=False): """ Sets up the will message :param topic: Topic of the will message :param payload: Content of the message :param qos: Quality of Service :param retain: The message will be retained :raise ValueError: Invalid topic :raise TypeError: Invalid payload """ self.__mqtt.will_set(topic, payload, qos, retain=retain)
Sets up the will message :param topic: Topic of the will message :param payload: Content of the message :param qos: Quality of Service :param retain: The message will be retained :raise ValueError: Invalid topic :raise TypeError: Invalid payload
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L194-L205
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.connect
def connect(self, host="localhost", port=1883, keepalive=60): """ Connects to the MQTT server. The client will automatically try to reconnect to this server when the connection is lost. :param host: MQTT server host :param port: MQTT server port :param keepalive: Maximum period in seconds between communications with the broker :raise ValueError: Invalid host or port """ # Disconnect first (it also stops the timer) self.disconnect() # Prepare the connection self.__mqtt.connect(host, port, keepalive) # Start the MQTT loop self.__mqtt.loop_start()
python
def connect(self, host="localhost", port=1883, keepalive=60): """ Connects to the MQTT server. The client will automatically try to reconnect to this server when the connection is lost. :param host: MQTT server host :param port: MQTT server port :param keepalive: Maximum period in seconds between communications with the broker :raise ValueError: Invalid host or port """ # Disconnect first (it also stops the timer) self.disconnect() # Prepare the connection self.__mqtt.connect(host, port, keepalive) # Start the MQTT loop self.__mqtt.loop_start()
Connects to the MQTT server. The client will automatically try to reconnect to this server when the connection is lost. :param host: MQTT server host :param port: MQTT server port :param keepalive: Maximum period in seconds between communications with the broker :raise ValueError: Invalid host or port
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L207-L225
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.disconnect
def disconnect(self): """ Disconnects from the MQTT server """ # Stop the timer self.__stop_timer() # Unlock all publishers for event in self.__in_flight.values(): event.set() # Disconnect from the server self.__mqtt.disconnect() # Stop the MQTT loop thread # Use a thread to avoid a dead lock in Paho thread = threading.Thread(target=self.__mqtt.loop_stop) thread.daemon = True thread.start() # Give it some time thread.join(4)
python
def disconnect(self): """ Disconnects from the MQTT server """ # Stop the timer self.__stop_timer() # Unlock all publishers for event in self.__in_flight.values(): event.set() # Disconnect from the server self.__mqtt.disconnect() # Stop the MQTT loop thread # Use a thread to avoid a dead lock in Paho thread = threading.Thread(target=self.__mqtt.loop_stop) thread.daemon = True thread.start() # Give it some time thread.join(4)
Disconnects from the MQTT server
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L227-L248
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.publish
def publish(self, topic, payload, qos=0, retain=False, wait=False): """ Sends a message through the MQTT connection :param topic: Message topic :param payload: Message content :param qos: Quality of Service :param retain: Retain flag :param wait: If True, prepares an event to wait for the message to be published :return: The local message ID, None on error """ result = self.__mqtt.publish(topic, payload, qos, retain) if wait and not result[0]: # Publish packet sent, wait for it to return self.__in_flight[result[1]] = threading.Event() _logger.debug("Waiting for publication of %s", topic) return result[1]
python
def publish(self, topic, payload, qos=0, retain=False, wait=False): """ Sends a message through the MQTT connection :param topic: Message topic :param payload: Message content :param qos: Quality of Service :param retain: Retain flag :param wait: If True, prepares an event to wait for the message to be published :return: The local message ID, None on error """ result = self.__mqtt.publish(topic, payload, qos, retain) if wait and not result[0]: # Publish packet sent, wait for it to return self.__in_flight[result[1]] = threading.Event() _logger.debug("Waiting for publication of %s", topic) return result[1]
Sends a message through the MQTT connection :param topic: Message topic :param payload: Message content :param qos: Quality of Service :param retain: Retain flag :param wait: If True, prepares an event to wait for the message to be published :return: The local message ID, None on error
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L250-L268
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.__start_timer
def __start_timer(self, delay): """ Starts the reconnection timer :param delay: Delay (in seconds) before calling the reconnection method """ self.__timer = threading.Timer(delay, self.__reconnect) self.__timer.daemon = True self.__timer.start()
python
def __start_timer(self, delay): """ Starts the reconnection timer :param delay: Delay (in seconds) before calling the reconnection method """ self.__timer = threading.Timer(delay, self.__reconnect) self.__timer.daemon = True self.__timer.start()
Starts the reconnection timer :param delay: Delay (in seconds) before calling the reconnection method
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L300-L308
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.__reconnect
def __reconnect(self): """ Tries to connect to the MQTT server """ # Cancel the timer, if any self.__stop_timer() try: # Try to reconnect the server result_code = self.__mqtt.reconnect() if result_code: # Something wrong happened message = "Error connecting the MQTT server: {0} ({1})".format( result_code, paho.error_string(result_code) ) _logger.error(message) raise ValueError(message) except Exception as ex: # Something went wrong: log it _logger.error("Exception connecting server: %s", ex) finally: # Prepare a reconnection timer. It will be cancelled by the # on_connect callback self.__start_timer(10)
python
def __reconnect(self): """ Tries to connect to the MQTT server """ # Cancel the timer, if any self.__stop_timer() try: # Try to reconnect the server result_code = self.__mqtt.reconnect() if result_code: # Something wrong happened message = "Error connecting the MQTT server: {0} ({1})".format( result_code, paho.error_string(result_code) ) _logger.error(message) raise ValueError(message) except Exception as ex: # Something went wrong: log it _logger.error("Exception connecting server: %s", ex) finally: # Prepare a reconnection timer. It will be cancelled by the # on_connect callback self.__start_timer(10)
Tries to connect to the MQTT server
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L318-L341
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.__on_connect
def __on_connect(self, client, userdata, flags, result_code): # pylint: disable=W0613 """ Client connected to the server :param client: Connected Paho client :param userdata: User data (unused) :param flags: Response flags sent by the broker :param result_code: Connection result code (0: success, others: error) """ if result_code: # result_code != 0: something wrong happened _logger.error( "Error connecting the MQTT server: %s (%d)", paho.connack_string(result_code), result_code, ) else: # Connection is OK: stop the reconnection timer self.__stop_timer() # Notify the caller, if any if self.on_connect is not None: try: self.on_connect(self, result_code) except Exception as ex: _logger.exception("Error notifying MQTT listener: %s", ex)
python
def __on_connect(self, client, userdata, flags, result_code): # pylint: disable=W0613 """ Client connected to the server :param client: Connected Paho client :param userdata: User data (unused) :param flags: Response flags sent by the broker :param result_code: Connection result code (0: success, others: error) """ if result_code: # result_code != 0: something wrong happened _logger.error( "Error connecting the MQTT server: %s (%d)", paho.connack_string(result_code), result_code, ) else: # Connection is OK: stop the reconnection timer self.__stop_timer() # Notify the caller, if any if self.on_connect is not None: try: self.on_connect(self, result_code) except Exception as ex: _logger.exception("Error notifying MQTT listener: %s", ex)
Client connected to the server :param client: Connected Paho client :param userdata: User data (unused) :param flags: Response flags sent by the broker :param result_code: Connection result code (0: success, others: error)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L343-L369
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.__on_disconnect
def __on_disconnect(self, client, userdata, result_code): # pylint: disable=W0613 """ Client has been disconnected from the server :param client: Client that received the message :param userdata: User data (unused) :param result_code: Disconnection reason (0: expected, 1: error) """ if result_code: # rc != 0: unexpected disconnection _logger.error( "Unexpected disconnection from the MQTT server: %s (%d)", paho.connack_string(result_code), result_code, ) # Try to reconnect self.__stop_timer() self.__start_timer(2) # Notify the caller, if any if self.on_disconnect is not None: try: self.on_disconnect(self, result_code) except Exception as ex: _logger.exception("Error notifying MQTT listener: %s", ex)
python
def __on_disconnect(self, client, userdata, result_code): # pylint: disable=W0613 """ Client has been disconnected from the server :param client: Client that received the message :param userdata: User data (unused) :param result_code: Disconnection reason (0: expected, 1: error) """ if result_code: # rc != 0: unexpected disconnection _logger.error( "Unexpected disconnection from the MQTT server: %s (%d)", paho.connack_string(result_code), result_code, ) # Try to reconnect self.__stop_timer() self.__start_timer(2) # Notify the caller, if any if self.on_disconnect is not None: try: self.on_disconnect(self, result_code) except Exception as ex: _logger.exception("Error notifying MQTT listener: %s", ex)
Client has been disconnected from the server :param client: Client that received the message :param userdata: User data (unused) :param result_code: Disconnection reason (0: expected, 1: error)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L371-L397
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.__on_message
def __on_message(self, client, userdata, msg): # pylint: disable=W0613 """ A message has been received from a server :param client: Client that received the message :param userdata: User data (unused) :param msg: A MQTTMessage bean """ # Notify the caller, if any if self.on_message is not None: try: self.on_message(self, msg) except Exception as ex: _logger.exception("Error notifying MQTT listener: %s", ex)
python
def __on_message(self, client, userdata, msg): # pylint: disable=W0613 """ A message has been received from a server :param client: Client that received the message :param userdata: User data (unused) :param msg: A MQTTMessage bean """ # Notify the caller, if any if self.on_message is not None: try: self.on_message(self, msg) except Exception as ex: _logger.exception("Error notifying MQTT listener: %s", ex)
A message has been received from a server :param client: Client that received the message :param userdata: User data (unused) :param msg: A MQTTMessage bean
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L399-L413
tcalmant/ipopo
pelix/misc/mqtt_client.py
MqttClient.__on_publish
def __on_publish(self, client, userdata, mid): # pylint: disable=W0613 """ A message has been published by a server :param client: Client that received the message :param userdata: User data (unused) :param mid: Message ID """ try: self.__in_flight[mid].set() except KeyError: pass
python
def __on_publish(self, client, userdata, mid): # pylint: disable=W0613 """ A message has been published by a server :param client: Client that received the message :param userdata: User data (unused) :param mid: Message ID """ try: self.__in_flight[mid].set() except KeyError: pass
A message has been published by a server :param client: Client that received the message :param userdata: User data (unused) :param mid: Message ID
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/mqtt_client.py#L415-L427
tcalmant/ipopo
pelix/remote/beans.py
to_import_properties
def to_import_properties(properties): # type: (dict) -> dict """ Returns a dictionary where export properties have been replaced by import ones :param properties: A dictionary of service properties (with export keys) :return: A dictionary with import properties """ # Copy the given dictionary props = properties.copy() # Add the "imported" property props[pelix.remote.PROP_IMPORTED] = True # Remote service ID try: props[pelix.remote.PROP_ENDPOINT_SERVICE_ID] = props.pop( pelix.constants.SERVICE_ID ) except KeyError: # No service ID pass # Replace the "export configs" configs = props.pop(pelix.remote.PROP_EXPORTED_CONFIGS, None) if configs: props[pelix.remote.PROP_IMPORTED_CONFIGS] = configs # Clear other export properties for key in ( pelix.remote.PROP_EXPORTED_INTENTS, pelix.remote.PROP_EXPORTED_INTENTS_EXTRA, pelix.remote.PROP_EXPORTED_INTERFACES, ): try: del props[key] except KeyError: # Key wasn't there pass return props
python
def to_import_properties(properties): # type: (dict) -> dict """ Returns a dictionary where export properties have been replaced by import ones :param properties: A dictionary of service properties (with export keys) :return: A dictionary with import properties """ # Copy the given dictionary props = properties.copy() # Add the "imported" property props[pelix.remote.PROP_IMPORTED] = True # Remote service ID try: props[pelix.remote.PROP_ENDPOINT_SERVICE_ID] = props.pop( pelix.constants.SERVICE_ID ) except KeyError: # No service ID pass # Replace the "export configs" configs = props.pop(pelix.remote.PROP_EXPORTED_CONFIGS, None) if configs: props[pelix.remote.PROP_IMPORTED_CONFIGS] = configs # Clear other export properties for key in ( pelix.remote.PROP_EXPORTED_INTENTS, pelix.remote.PROP_EXPORTED_INTENTS_EXTRA, pelix.remote.PROP_EXPORTED_INTERFACES, ): try: del props[key] except KeyError: # Key wasn't there pass return props
Returns a dictionary where export properties have been replaced by import ones :param properties: A dictionary of service properties (with export keys) :return: A dictionary with import properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L699-L740
tcalmant/ipopo
pelix/remote/beans.py
compute_exported_specifications
def compute_exported_specifications(svc_ref): # type: (pelix.framework.ServiceReference) -> List[str] """ Computes the list of specifications exported by the given service :param svc_ref: A ServiceReference :return: The list of exported specifications (or an empty list) """ if svc_ref.get_property(pelix.remote.PROP_EXPORT_NONE): # The export of this service is explicitly forbidden, stop here return [] # Service specifications specs = svc_ref.get_property(pelix.constants.OBJECTCLASS) # Exported specifications exported_specs = svc_ref.get_property(pelix.remote.PROP_EXPORTED_INTERFACES) if exported_specs and exported_specs != "*": # A set of specifications is exported, replace "objectClass" iterable_exports = pelix.utilities.to_iterable(exported_specs, False) all_exported_specs = [ spec for spec in specs if spec in iterable_exports ] else: # Export everything all_exported_specs = pelix.utilities.to_iterable(specs) # Authorized and rejected specifications export_only_specs = pelix.utilities.to_iterable( svc_ref.get_property(pelix.remote.PROP_EXPORT_ONLY), False ) if export_only_specs: # Filter specifications (keep authorized specifications) return [ spec for spec in all_exported_specs if spec in export_only_specs ] # Filter specifications (reject) rejected_specs = pelix.utilities.to_iterable( svc_ref.get_property(pelix.remote.PROP_EXPORT_REJECT), False ) return [spec for spec in all_exported_specs if spec not in rejected_specs]
python
def compute_exported_specifications(svc_ref): # type: (pelix.framework.ServiceReference) -> List[str] """ Computes the list of specifications exported by the given service :param svc_ref: A ServiceReference :return: The list of exported specifications (or an empty list) """ if svc_ref.get_property(pelix.remote.PROP_EXPORT_NONE): # The export of this service is explicitly forbidden, stop here return [] # Service specifications specs = svc_ref.get_property(pelix.constants.OBJECTCLASS) # Exported specifications exported_specs = svc_ref.get_property(pelix.remote.PROP_EXPORTED_INTERFACES) if exported_specs and exported_specs != "*": # A set of specifications is exported, replace "objectClass" iterable_exports = pelix.utilities.to_iterable(exported_specs, False) all_exported_specs = [ spec for spec in specs if spec in iterable_exports ] else: # Export everything all_exported_specs = pelix.utilities.to_iterable(specs) # Authorized and rejected specifications export_only_specs = pelix.utilities.to_iterable( svc_ref.get_property(pelix.remote.PROP_EXPORT_ONLY), False ) if export_only_specs: # Filter specifications (keep authorized specifications) return [ spec for spec in all_exported_specs if spec in export_only_specs ] # Filter specifications (reject) rejected_specs = pelix.utilities.to_iterable( svc_ref.get_property(pelix.remote.PROP_EXPORT_REJECT), False ) return [spec for spec in all_exported_specs if spec not in rejected_specs]
Computes the list of specifications exported by the given service :param svc_ref: A ServiceReference :return: The list of exported specifications (or an empty list)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L746-L789
tcalmant/ipopo
pelix/remote/beans.py
extract_specifications
def extract_specifications(specifications, properties): # type: (Any[str, List[str]], dict) -> List[str] """ Converts "python:/name" specifications to "name". Keeps the other specifications as is. :param specifications: The specifications found in a remote registration :param properties: Service properties :return: The filtered specifications (as a list) """ all_specs = set(pelix.utilities.to_iterable(specifications)) try: synonyms = pelix.utilities.to_iterable( properties[pelix.remote.PROP_SYNONYMS], False ) all_specs.update(synonyms) except KeyError: # No synonyms property pass filtered_specs = set() for original in all_specs: try: # Extract information lang, spec = _extract_specification_parts(original) if lang == PYTHON_LANGUAGE: # Language match: keep the name only filtered_specs.add(spec) else: # Keep the name as is filtered_specs.add(original) except ValueError: # Ignore invalid specifications pass return list(filtered_specs)
python
def extract_specifications(specifications, properties): # type: (Any[str, List[str]], dict) -> List[str] """ Converts "python:/name" specifications to "name". Keeps the other specifications as is. :param specifications: The specifications found in a remote registration :param properties: Service properties :return: The filtered specifications (as a list) """ all_specs = set(pelix.utilities.to_iterable(specifications)) try: synonyms = pelix.utilities.to_iterable( properties[pelix.remote.PROP_SYNONYMS], False ) all_specs.update(synonyms) except KeyError: # No synonyms property pass filtered_specs = set() for original in all_specs: try: # Extract information lang, spec = _extract_specification_parts(original) if lang == PYTHON_LANGUAGE: # Language match: keep the name only filtered_specs.add(spec) else: # Keep the name as is filtered_specs.add(original) except ValueError: # Ignore invalid specifications pass return list(filtered_specs)
Converts "python:/name" specifications to "name". Keeps the other specifications as is. :param specifications: The specifications found in a remote registration :param properties: Service properties :return: The filtered specifications (as a list)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L792-L827
tcalmant/ipopo
pelix/remote/beans.py
format_specifications
def format_specifications(specifications): # type: (Iterable[str]) -> List[str] """ Transforms the interfaces names into URI strings, with the interface implementation language as a scheme. :param specifications: Specifications to transform :return: The transformed names """ transformed = set() for original in specifications: try: lang, spec = _extract_specification_parts(original) transformed.add(_format_specification(lang, spec)) except ValueError: # Ignore invalid specifications pass return list(transformed)
python
def format_specifications(specifications): # type: (Iterable[str]) -> List[str] """ Transforms the interfaces names into URI strings, with the interface implementation language as a scheme. :param specifications: Specifications to transform :return: The transformed names """ transformed = set() for original in specifications: try: lang, spec = _extract_specification_parts(original) transformed.add(_format_specification(lang, spec)) except ValueError: # Ignore invalid specifications pass return list(transformed)
Transforms the interfaces names into URI strings, with the interface implementation language as a scheme. :param specifications: Specifications to transform :return: The transformed names
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L830-L848
tcalmant/ipopo
pelix/remote/beans.py
_extract_specification_parts
def _extract_specification_parts(specification): # type: (str) -> Tuple[str, str] """ Extract the language and the interface from a "language:/interface" interface name :param specification: The formatted interface name :return: A (language, interface name) tuple :raise ValueError: Invalid specification content """ try: # Parse the URI-like string parsed = urlparse(specification) except: # Invalid URL raise ValueError("Invalid specification URL: {0}".format(specification)) # Extract the interface name interface = parsed.path # Extract the language, if given language = parsed.scheme if not language: # Simple name, without scheme language = PYTHON_LANGUAGE else: # Formatted name: un-escape it, without the starting '/' interface = _unescape_specification(interface[1:]) return language, interface
python
def _extract_specification_parts(specification): # type: (str) -> Tuple[str, str] """ Extract the language and the interface from a "language:/interface" interface name :param specification: The formatted interface name :return: A (language, interface name) tuple :raise ValueError: Invalid specification content """ try: # Parse the URI-like string parsed = urlparse(specification) except: # Invalid URL raise ValueError("Invalid specification URL: {0}".format(specification)) # Extract the interface name interface = parsed.path # Extract the language, if given language = parsed.scheme if not language: # Simple name, without scheme language = PYTHON_LANGUAGE else: # Formatted name: un-escape it, without the starting '/' interface = _unescape_specification(interface[1:]) return language, interface
Extract the language and the interface from a "language:/interface" interface name :param specification: The formatted interface name :return: A (language, interface name) tuple :raise ValueError: Invalid specification content
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L851-L880
tcalmant/ipopo
pelix/remote/beans.py
ExportEndpoint.get_properties
def get_properties(self): # type: () -> dict """ Returns merged properties :return: Endpoint merged properties """ # Get service properties properties = self.__reference.get_properties() # Merge with local properties properties.update(self.__properties) # Some properties can't be merged for key in pelix.constants.OBJECTCLASS, pelix.constants.SERVICE_ID: properties[key] = self.__reference.get_property(key) # Force the exported configurations properties[pelix.remote.PROP_EXPORTED_CONFIGS] = self.configurations return properties
python
def get_properties(self): # type: () -> dict """ Returns merged properties :return: Endpoint merged properties """ # Get service properties properties = self.__reference.get_properties() # Merge with local properties properties.update(self.__properties) # Some properties can't be merged for key in pelix.constants.OBJECTCLASS, pelix.constants.SERVICE_ID: properties[key] = self.__reference.get_property(key) # Force the exported configurations properties[pelix.remote.PROP_EXPORTED_CONFIGS] = self.configurations return properties
Returns merged properties :return: Endpoint merged properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L152-L172
tcalmant/ipopo
pelix/remote/beans.py
ExportEndpoint.make_import_properties
def make_import_properties(self): # type: () -> dict """ Returns the properties of this endpoint where export properties have been replaced by import ones :return: A dictionary with import properties """ # Convert merged properties props = to_import_properties(self.get_properties()) # Add the framework UID props[pelix.remote.PROP_ENDPOINT_FRAMEWORK_UUID] = self.__fw_uid return props
python
def make_import_properties(self): # type: () -> dict """ Returns the properties of this endpoint where export properties have been replaced by import ones :return: A dictionary with import properties """ # Convert merged properties props = to_import_properties(self.get_properties()) # Add the framework UID props[pelix.remote.PROP_ENDPOINT_FRAMEWORK_UUID] = self.__fw_uid return props
Returns the properties of this endpoint where export properties have been replaced by import ones :return: A dictionary with import properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L174-L187
tcalmant/ipopo
pelix/remote/beans.py
EndpointDescription.__check_properties
def __check_properties(props): # type: (dict) -> None """ Checks that the given dictionary doesn't have export keys and has import keys :param props: Properties to validate :raise ValueError: Invalid properties """ # Mandatory properties mandatory = ( pelix.remote.PROP_ENDPOINT_ID, pelix.remote.PROP_IMPORTED_CONFIGS, pelix.constants.OBJECTCLASS, ) for key in mandatory: if key not in props: raise ValueError("Missing property: {0}".format(key)) # Export/Import properties props_export = ( pelix.remote.PROP_EXPORTED_CONFIGS, pelix.remote.PROP_EXPORTED_INTERFACES, ) for key in props_export: if key in props: raise ValueError("Export property found: {0}".format(key))
python
def __check_properties(props): # type: (dict) -> None """ Checks that the given dictionary doesn't have export keys and has import keys :param props: Properties to validate :raise ValueError: Invalid properties """ # Mandatory properties mandatory = ( pelix.remote.PROP_ENDPOINT_ID, pelix.remote.PROP_IMPORTED_CONFIGS, pelix.constants.OBJECTCLASS, ) for key in mandatory: if key not in props: raise ValueError("Missing property: {0}".format(key)) # Export/Import properties props_export = ( pelix.remote.PROP_EXPORTED_CONFIGS, pelix.remote.PROP_EXPORTED_INTERFACES, ) for key in props_export: if key in props: raise ValueError("Export property found: {0}".format(key))
Checks that the given dictionary doesn't have export keys and has import keys :param props: Properties to validate :raise ValueError: Invalid properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L452-L479
tcalmant/ipopo
pelix/remote/beans.py
EndpointDescription.get_package_version
def get_package_version(self, package): # type: (str) -> Tuple[int, ...] """ Provides the version of the given package name. :param package: The name of the package :return: The version of the specified package as a tuple or (0,0,0) """ name = "{0}{1}".format( pelix.remote.PROP_ENDPOINT_PACKAGE_VERSION_, package ) try: # Get the version string version = self.__properties[name] # Split dots ('.') return tuple(version.split(".")) except KeyError: # No version return 0, 0, 0
python
def get_package_version(self, package): # type: (str) -> Tuple[int, ...] """ Provides the version of the given package name. :param package: The name of the package :return: The version of the specified package as a tuple or (0,0,0) """ name = "{0}{1}".format( pelix.remote.PROP_ENDPOINT_PACKAGE_VERSION_, package ) try: # Get the version string version = self.__properties[name] # Split dots ('.') return tuple(version.split(".")) except KeyError: # No version return 0, 0, 0
Provides the version of the given package name. :param package: The name of the package :return: The version of the specified package as a tuple or (0,0,0)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L548-L567
tcalmant/ipopo
pelix/remote/beans.py
EndpointDescription.matches
def matches(self, ldap_filter): # type: (Any[str, pelix.ldapfilter.LDAPFilter]) -> bool """ Tests the properties of this EndpointDescription against the given filter :param ldap_filter: A filter :return: True if properties matches the filter """ return pelix.ldapfilter.get_ldap_filter(ldap_filter).matches( self.__properties )
python
def matches(self, ldap_filter): # type: (Any[str, pelix.ldapfilter.LDAPFilter]) -> bool """ Tests the properties of this EndpointDescription against the given filter :param ldap_filter: A filter :return: True if properties matches the filter """ return pelix.ldapfilter.get_ldap_filter(ldap_filter).matches( self.__properties )
Tests the properties of this EndpointDescription against the given filter :param ldap_filter: A filter :return: True if properties matches the filter
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L605-L616
tcalmant/ipopo
pelix/remote/beans.py
EndpointDescription.to_import
def to_import(self): # type: () -> ImportEndpoint """ Converts an EndpointDescription bean to an ImportEndpoint :return: An ImportEndpoint bean """ # Properties properties = self.get_properties() # Framework UUID fw_uid = self.get_framework_uuid() # Endpoint name try: # From Pelix UID name = properties[pelix.remote.PROP_ENDPOINT_NAME] except KeyError: # Generated name = "{0}.{1}".format(fw_uid, self.get_service_id()) # Configuration / kind configurations = self.get_configuration_types() # Interfaces specifications = self.get_interfaces() return ImportEndpoint( self.get_id(), fw_uid, configurations, name, specifications, properties, )
python
def to_import(self): # type: () -> ImportEndpoint """ Converts an EndpointDescription bean to an ImportEndpoint :return: An ImportEndpoint bean """ # Properties properties = self.get_properties() # Framework UUID fw_uid = self.get_framework_uuid() # Endpoint name try: # From Pelix UID name = properties[pelix.remote.PROP_ENDPOINT_NAME] except KeyError: # Generated name = "{0}.{1}".format(fw_uid, self.get_service_id()) # Configuration / kind configurations = self.get_configuration_types() # Interfaces specifications = self.get_interfaces() return ImportEndpoint( self.get_id(), fw_uid, configurations, name, specifications, properties, )
Converts an EndpointDescription bean to an ImportEndpoint :return: An ImportEndpoint bean
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L618-L652
tcalmant/ipopo
pelix/remote/beans.py
EndpointDescription.from_export
def from_export(cls, endpoint): # type: (ExportEndpoint) -> EndpointDescription """ Converts an ExportEndpoint bean to an EndpointDescription :param endpoint: An ExportEndpoint bean :return: An EndpointDescription bean """ assert isinstance(endpoint, ExportEndpoint) # Service properties properties = endpoint.get_properties() # Set import keys properties[pelix.remote.PROP_ENDPOINT_ID] = endpoint.uid properties[pelix.remote.PROP_IMPORTED_CONFIGS] = endpoint.configurations properties[ pelix.remote.PROP_EXPORTED_INTERFACES ] = endpoint.specifications # Remove export keys for key in ( pelix.remote.PROP_EXPORTED_CONFIGS, pelix.remote.PROP_EXPORTED_INTERFACES, pelix.remote.PROP_EXPORTED_INTENTS, pelix.remote.PROP_EXPORTED_INTENTS_EXTRA, ): try: del properties[key] except KeyError: pass # Other information properties[pelix.remote.PROP_ENDPOINT_NAME] = endpoint.name properties[ pelix.remote.PROP_ENDPOINT_FRAMEWORK_UUID ] = endpoint.framework return EndpointDescription(None, properties)
python
def from_export(cls, endpoint): # type: (ExportEndpoint) -> EndpointDescription """ Converts an ExportEndpoint bean to an EndpointDescription :param endpoint: An ExportEndpoint bean :return: An EndpointDescription bean """ assert isinstance(endpoint, ExportEndpoint) # Service properties properties = endpoint.get_properties() # Set import keys properties[pelix.remote.PROP_ENDPOINT_ID] = endpoint.uid properties[pelix.remote.PROP_IMPORTED_CONFIGS] = endpoint.configurations properties[ pelix.remote.PROP_EXPORTED_INTERFACES ] = endpoint.specifications # Remove export keys for key in ( pelix.remote.PROP_EXPORTED_CONFIGS, pelix.remote.PROP_EXPORTED_INTERFACES, pelix.remote.PROP_EXPORTED_INTENTS, pelix.remote.PROP_EXPORTED_INTENTS_EXTRA, ): try: del properties[key] except KeyError: pass # Other information properties[pelix.remote.PROP_ENDPOINT_NAME] = endpoint.name properties[ pelix.remote.PROP_ENDPOINT_FRAMEWORK_UUID ] = endpoint.framework return EndpointDescription(None, properties)
Converts an ExportEndpoint bean to an EndpointDescription :param endpoint: An ExportEndpoint bean :return: An EndpointDescription bean
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/beans.py#L655-L693
tcalmant/ipopo
pelix/rsa/edef.py
EDEFReader._parse_description
def _parse_description(self, node): # type: (ElementTree.Element) -> EndpointDescription """ Parse an endpoint description node :param node: The endpoint description node :return: The parsed EndpointDescription bean :raise KeyError: Attribute missing :raise ValueError: Invalid description """ endpoint = {} for prop_node in node.findall(TAG_PROPERTY): name, value = self._parse_property(prop_node) endpoint[name] = value return EndpointDescription(None, endpoint)
python
def _parse_description(self, node): # type: (ElementTree.Element) -> EndpointDescription """ Parse an endpoint description node :param node: The endpoint description node :return: The parsed EndpointDescription bean :raise KeyError: Attribute missing :raise ValueError: Invalid description """ endpoint = {} for prop_node in node.findall(TAG_PROPERTY): name, value = self._parse_property(prop_node) endpoint[name] = value return EndpointDescription(None, endpoint)
Parse an endpoint description node :param node: The endpoint description node :return: The parsed EndpointDescription bean :raise KeyError: Attribute missing :raise ValueError: Invalid description
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/edef.py#L165-L180
tcalmant/ipopo
pelix/rsa/edef.py
EDEFReader._parse_property
def _parse_property(self, node): # type: (ElementTree.Element) -> Tuple[str, Any] """ Parses a property node :param node: The property node :return: A (name, value) tuple :raise KeyError: Attribute missing """ # Get information name = node.attrib[ATTR_NAME] vtype = node.attrib.get(ATTR_VALUE_TYPE, TYPE_STRING) # Look for a value as a single child node try: value_node = next(iter(node)) value = self._parse_value_node(vtype, value_node) except StopIteration: # Value is an attribute value = self._convert_value(vtype, node.attrib[ATTR_VALUE]) return name, value
python
def _parse_property(self, node): # type: (ElementTree.Element) -> Tuple[str, Any] """ Parses a property node :param node: The property node :return: A (name, value) tuple :raise KeyError: Attribute missing """ # Get information name = node.attrib[ATTR_NAME] vtype = node.attrib.get(ATTR_VALUE_TYPE, TYPE_STRING) # Look for a value as a single child node try: value_node = next(iter(node)) value = self._parse_value_node(vtype, value_node) except StopIteration: # Value is an attribute value = self._convert_value(vtype, node.attrib[ATTR_VALUE]) return name, value
Parses a property node :param node: The property node :return: A (name, value) tuple :raise KeyError: Attribute missing
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/edef.py#L182-L203
tcalmant/ipopo
pelix/rsa/edef.py
EDEFReader._parse_value_node
def _parse_value_node(self, vtype, node): # type: (str, ElementTree.Element) -> Any """ Parses a value node :param vtype: The value type :param node: The value node :return: The parsed value """ kind = node.tag if kind == TAG_XML: # Raw XML value return next(iter(node)) elif kind == TAG_LIST or kind == TAG_ARRAY: # List return [ self._convert_value(vtype, value_node.text) for value_node in node.findall(TAG_VALUE) ] elif kind == TAG_SET: # Set return set( self._convert_value(vtype, value_node.text) for value_node in node.findall(TAG_VALUE) ) else: # Unknown raise ValueError("Unknown value tag: {0}".format(kind))
python
def _parse_value_node(self, vtype, node): # type: (str, ElementTree.Element) -> Any """ Parses a value node :param vtype: The value type :param node: The value node :return: The parsed value """ kind = node.tag if kind == TAG_XML: # Raw XML value return next(iter(node)) elif kind == TAG_LIST or kind == TAG_ARRAY: # List return [ self._convert_value(vtype, value_node.text) for value_node in node.findall(TAG_VALUE) ] elif kind == TAG_SET: # Set return set( self._convert_value(vtype, value_node.text) for value_node in node.findall(TAG_VALUE) ) else: # Unknown raise ValueError("Unknown value tag: {0}".format(kind))
Parses a value node :param vtype: The value type :param node: The value node :return: The parsed value
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/edef.py#L205-L235
tcalmant/ipopo
pelix/rsa/edef.py
EDEFReader.parse
def parse(self, xml_str): # type: (str) -> List[EndpointDescription] """ Parses an EDEF XML string :param xml_str: An XML string :return: The list of parsed EndpointDescription """ # Parse the document root = ElementTree.fromstring(xml_str) if root.tag != TAG_ENDPOINT_DESCRIPTIONS: raise ValueError("Not an EDEF XML: {0}".format(root.tag)) # Parse content return [ self._parse_description(node) for node in root.findall(TAG_ENDPOINT_DESCRIPTION) ]
python
def parse(self, xml_str): # type: (str) -> List[EndpointDescription] """ Parses an EDEF XML string :param xml_str: An XML string :return: The list of parsed EndpointDescription """ # Parse the document root = ElementTree.fromstring(xml_str) if root.tag != TAG_ENDPOINT_DESCRIPTIONS: raise ValueError("Not an EDEF XML: {0}".format(root.tag)) # Parse content return [ self._parse_description(node) for node in root.findall(TAG_ENDPOINT_DESCRIPTION) ]
Parses an EDEF XML string :param xml_str: An XML string :return: The list of parsed EndpointDescription
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/edef.py#L237-L254
tcalmant/ipopo
pelix/rsa/edef.py
EDEFWriter._make_endpoint
def _make_endpoint(self, root_node, endpoint): # type: (ElementTree.Element, EndpointDescription) -> None """ Converts the given endpoint bean to an XML Element :param root_node: The XML root Element :param endpoint: An EndpointDescription bean """ endpoint_node = ElementTree.SubElement( root_node, TAG_ENDPOINT_DESCRIPTION ) for name, value in endpoint.get_properties().items(): # Compute value type vtype = self._get_type(name, value) # Prepare the property node prop_node = ElementTree.SubElement( endpoint_node, TAG_PROPERTY, {ATTR_NAME: name} ) if vtype == XML_VALUE: # Special case, we have to store the value as a child # without a value-type attribute prop_node.append(value) continue # Set the value type prop_node.set(ATTR_VALUE_TYPE, vtype) # Compute value node or attribute if isinstance(value, tuple): # Array self._add_container(prop_node, TAG_ARRAY, value) elif isinstance(value, list): # List self._add_container(prop_node, TAG_ARRAY, value) elif isinstance(value, set): # Set self._add_container(prop_node, TAG_SET, value) elif isinstance(value, type(root_node)): # XML (direct addition) prop_node.append(value) else: # Simple value -> Attribute prop_node.set(ATTR_VALUE, str(value))
python
def _make_endpoint(self, root_node, endpoint): # type: (ElementTree.Element, EndpointDescription) -> None """ Converts the given endpoint bean to an XML Element :param root_node: The XML root Element :param endpoint: An EndpointDescription bean """ endpoint_node = ElementTree.SubElement( root_node, TAG_ENDPOINT_DESCRIPTION ) for name, value in endpoint.get_properties().items(): # Compute value type vtype = self._get_type(name, value) # Prepare the property node prop_node = ElementTree.SubElement( endpoint_node, TAG_PROPERTY, {ATTR_NAME: name} ) if vtype == XML_VALUE: # Special case, we have to store the value as a child # without a value-type attribute prop_node.append(value) continue # Set the value type prop_node.set(ATTR_VALUE_TYPE, vtype) # Compute value node or attribute if isinstance(value, tuple): # Array self._add_container(prop_node, TAG_ARRAY, value) elif isinstance(value, list): # List self._add_container(prop_node, TAG_ARRAY, value) elif isinstance(value, set): # Set self._add_container(prop_node, TAG_SET, value) elif isinstance(value, type(root_node)): # XML (direct addition) prop_node.append(value) else: # Simple value -> Attribute prop_node.set(ATTR_VALUE, str(value))
Converts the given endpoint bean to an XML Element :param root_node: The XML root Element :param endpoint: An EndpointDescription bean
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/edef.py#L373-L422
tcalmant/ipopo
pelix/rsa/edef.py
EDEFWriter._make_xml
def _make_xml(self, endpoints): # type: (List[EndpointDescription]) -> ElementTree.Element """ Converts the given endpoint description beans into an XML Element :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document """ root = ElementTree.Element(TAG_ENDPOINT_DESCRIPTIONS) for endpoint in endpoints: self._make_endpoint(root, endpoint) # Prepare pretty-printing self._indent(root) return root
python
def _make_xml(self, endpoints): # type: (List[EndpointDescription]) -> ElementTree.Element """ Converts the given endpoint description beans into an XML Element :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document """ root = ElementTree.Element(TAG_ENDPOINT_DESCRIPTIONS) for endpoint in endpoints: self._make_endpoint(root, endpoint) # Prepare pretty-printing self._indent(root) return root
Converts the given endpoint description beans into an XML Element :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/edef.py#L424-L438
tcalmant/ipopo
pelix/rsa/edef.py
EDEFWriter.to_string
def to_string(self, endpoints): # type: (List[EndpointDescription]) -> str """ 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 # Prepare a StringIO output output = StringIO() # Try to write with a correct encoding tree.write( output, encoding=self._encoding, xml_declaration=self._xml_declaration, ) return output.getvalue().strip()
python
def to_string(self, endpoints): # type: (List[EndpointDescription]) -> str """ 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 # Prepare a StringIO output output = StringIO() # Try to write with a correct encoding tree.write( output, encoding=self._encoding, xml_declaration=self._xml_declaration, ) return output.getvalue().strip()
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/rsa/edef.py#L440-L466
tcalmant/ipopo
pelix/rsa/edef.py
EDEFWriter.write
def write(self, endpoints, filename): # type: (List[EndpointDescription], str) -> None """ Writes the given endpoint descriptions to the given file :param endpoints: A list of EndpointDescription beans :param filename: Name of the file where to write the XML :raise IOError: Error writing the file """ with open(filename, "w") as filep: filep.write(self.to_string(endpoints))
python
def write(self, endpoints, filename): # type: (List[EndpointDescription], str) -> None """ Writes the given endpoint descriptions to the given file :param endpoints: A list of EndpointDescription beans :param filename: Name of the file where to write the XML :raise IOError: Error writing the file """ with open(filename, "w") as filep: filep.write(self.to_string(endpoints))
Writes the given endpoint descriptions to the given file :param endpoints: A list of EndpointDescription beans :param filename: Name of the file where to write the XML :raise IOError: Error writing the file
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/edef.py#L468-L478
tcalmant/ipopo
pelix/ipopo/decorators.py
is_from_parent
def is_from_parent(cls, attribute_name, value=None): # type: (type, str, bool) -> bool """ Tests if the current attribute value is shared by a parent of the given class. Returns None if the attribute value is None. :param cls: Child class with the requested attribute :param attribute_name: Name of the attribute to be tested :param value: The exact value in the child class (optional) :return: True if the attribute value is shared with a parent class """ if value is None: try: # Get the current value value = getattr(cls, attribute_name) except AttributeError: # No need to go further: the attribute does not exist return False for base in cls.__bases__: # Look for the value in each parent class try: return getattr(base, attribute_name) is value except AttributeError: pass # Attribute value not found in parent classes return False
python
def is_from_parent(cls, attribute_name, value=None): # type: (type, str, bool) -> bool """ Tests if the current attribute value is shared by a parent of the given class. Returns None if the attribute value is None. :param cls: Child class with the requested attribute :param attribute_name: Name of the attribute to be tested :param value: The exact value in the child class (optional) :return: True if the attribute value is shared with a parent class """ if value is None: try: # Get the current value value = getattr(cls, attribute_name) except AttributeError: # No need to go further: the attribute does not exist return False for base in cls.__bases__: # Look for the value in each parent class try: return getattr(base, attribute_name) is value except AttributeError: pass # Attribute value not found in parent classes return False
Tests if the current attribute value is shared by a parent of the given class. Returns None if the attribute value is None. :param cls: Child class with the requested attribute :param attribute_name: Name of the attribute to be tested :param value: The exact value in the child class (optional) :return: True if the attribute value is shared with a parent class
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L64-L93