code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
# Validate the path
if not path:
raise ValueError("Empty path")
elif not is_string(path):
raise ValueError("Path must be a string")
# Validate the visitor
if visitor is None:
raise ValueError("No visitor method given")
# Use an absolute path
path = os.path.abspath(path)
if not os.path.exists(path):
raise ValueError("Inexistent path: {0}".format(path))
# Set up the prefix if needed
if prefix is None:
prefix = os.path.basename(path)
bundles = set()
failed = set()
with self.__bundles_lock:
# Walk through the folder to find modules
for name, is_package in walk_modules(path):
# Ignore '__main__' modules
if name == "__main__":
continue
# Compute the full name of the module
fullname = ".".join((prefix, name)) if prefix else name
try:
if visitor(fullname, is_package, path):
if is_package:
# Install the package
bundles.add(self.install_bundle(fullname, path))
# Visit the package
sub_path = os.path.join(path, name)
sub_bundles, sub_failed = self.install_visiting(
sub_path, visitor, fullname
)
bundles.update(sub_bundles)
failed.update(sub_failed)
else:
# Install the bundle
bundles.add(self.install_bundle(fullname, path))
except BundleException as ex:
# Error loading the module
_logger.warning("Error visiting %s: %s", fullname, ex)
# Try the next module
failed.add(fullname)
continue
return bundles, failed
|
def install_visiting(self, path, visitor, prefix=None)
|
Installs all the modules found in the given path if they are accepted
by the visitor.
The visitor must be a callable accepting 3 parameters:
* fullname: The full name of the module
* is_package: If True, the module is a package
* module_path: The path to the module file
:param path: Root search path
:param visitor: The visiting callable
:param prefix: (**internal**) Prefix for all found modules
:return: A 2-tuple, with the list of installed bundles and the list
of failed modules names
:raise ValueError: Invalid path or visitor
| 2.83794
| 2.563355
| 1.107119
|
# type: (Bundle, Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration
if bundle is None or service is None or not clazz:
raise BundleException("Invalid registration parameters")
if not isinstance(properties, dict):
# Be sure we have a valid dictionary
properties = {}
else:
# Use a copy of the given properties
properties = properties.copy()
# Prepare the class specification
if not isinstance(clazz, (list, tuple)):
# Make a list from the single class
clazz = [clazz]
# Test the list content
classes = []
for svc_clazz in clazz:
if inspect.isclass(svc_clazz):
# Keep the type name
svc_clazz = svc_clazz.__name__
if not svc_clazz or not is_string(svc_clazz):
# Invalid class name
raise BundleException(
"Invalid class name: {0}".format(svc_clazz)
)
# Class OK
classes.append(svc_clazz)
# Make the service registration
registration = self._registry.register(
bundle, classes, properties, service, factory, prototype
)
# Update the bundle registration information
bundle._registered_service(registration)
if send_event:
# Call the listeners
event = ServiceEvent(
ServiceEvent.REGISTERED, registration.get_reference()
)
self._dispatcher.fire_service_event(event)
return registration
|
def register_service(
self,
bundle,
clazz,
service,
properties,
send_event,
factory=False,
prototype=False,
)
|
Registers a service and calls the listeners
:param bundle: The bundle registering the service
:param clazz: Name(s) of the interface(s) implemented by service
:param service: The service to register
:param properties: Service properties
: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
| 3.416272
| 3.548625
| 0.962703
|
# type: () -> bool
with self._lock:
if self._state in (Bundle.STARTING, Bundle.ACTIVE):
# Already started framework
return False
# Reset the stop event
self._fw_stop_event.clear()
# Starting...
self._state = Bundle.STARTING
self._dispatcher.fire_bundle_event(
BundleEvent(BundleEvent.STARTING, self)
)
# Start all registered bundles (use a copy, just in case...)
for bundle in self.__bundles.copy().values():
try:
bundle.start()
except FrameworkException as ex:
# Important error
_logger.exception(
"Important error starting bundle: %s", bundle
)
if ex.needs_stop:
# Stop the framework (has to be in active state)
self._state = Bundle.ACTIVE
self.stop()
return False
except BundleException:
# A bundle failed to start : just log
_logger.exception("Error starting bundle: %s", bundle)
# Bundle is now active
self._state = Bundle.ACTIVE
return True
|
def start(self)
|
Starts the framework
:return: True if the bundle has been started, False if it was already
running
:raise BundleException: A bundle failed to start
| 4.377243
| 4.275373
| 1.023827
|
# type: () -> bool
with self._lock:
if self._state != Bundle.ACTIVE:
# Invalid state
return False
# Hide all services (they will be deleted by bundle.stop())
for bundle in self.__bundles.values():
self._registry.hide_bundle_services(bundle)
# Stopping...
self._state = Bundle.STOPPING
self._dispatcher.fire_bundle_event(
BundleEvent(BundleEvent.STOPPING, self)
)
# Notify listeners that the bundle is stopping
self._dispatcher.fire_framework_stopping()
bid = self.__next_bundle_id - 1
while bid > 0:
bundle = self.__bundles.get(bid)
bid -= 1
if bundle is None or bundle.get_state() != Bundle.ACTIVE:
# Ignore inactive bundle
continue
try:
bundle.stop()
except Exception as ex:
# Just log exceptions
_logger.exception(
"Error stopping bundle %s: %s",
bundle.get_symbolic_name(),
ex,
)
# Framework is now stopped
self._state = Bundle.RESOLVED
self._dispatcher.fire_bundle_event(
BundleEvent(BundleEvent.STOPPED, self)
)
# All bundles have been stopped, release "wait_for_stop"
self._fw_stop_event.set()
# Force the registry clean up
self._registry.clear()
return True
|
def stop(self)
|
Stops the framework
:return: True if the framework stopped, False it wasn't running
| 3.69662
| 3.655204
| 1.011331
|
if not force and self._state not in (
Bundle.INSTALLED,
Bundle.RESOLVED,
Bundle.STOPPING,
):
_logger.warning("Trying to delete an active framework")
return False
return FrameworkFactory.delete_framework(self)
|
def delete(self, force=False)
|
Deletes the current framework
:param force: If True, stops the framework before deleting it
:return: True if the framework has been delete, False if is couldn't
| 7.27061
| 6.244706
| 1.164284
|
# type: (Bundle) -> None
if bundle is None:
# Do nothing
return
with self.__bundles_lock:
# Stop the bundle first
bundle.stop()
bundle_id = bundle.get_bundle_id()
if bundle_id not in self.__bundles:
raise BundleException("Invalid bundle {0}".format(bundle))
# Notify listeners
self._dispatcher.fire_bundle_event(
BundleEvent(BundleEvent.UNINSTALLED, bundle)
)
# Remove it from the dictionary
del self.__bundles[bundle_id]
# Remove it from the system => avoid unintended behaviors and
# forces a complete module reload if it is re-installed
name = bundle.get_symbolic_name()
try:
del sys.modules[name]
except KeyError:
# Ignore
pass
try:
# Clear reference in parent
parent, basename = name.rsplit(".", 1)
if parent:
delattr(sys.modules[parent], basename)
except (KeyError, AttributeError, ValueError):
# Ignore errors
pass
|
def uninstall_bundle(self, bundle)
|
Ends the uninstallation of the given bundle (must be called by Bundle)
:param bundle: The bundle to uninstall
:raise BundleException: Invalid bundle
| 4.012131
| 4.130126
| 0.971431
|
# type: (ServiceRegistration) -> bool
# Get the Service Reference
reference = registration.get_reference()
# Remove the service from the registry
svc_instance = self._registry.unregister(reference)
# Keep a track of the unregistering reference
self.__unregistering_services[reference] = svc_instance
# Call the listeners
event = ServiceEvent(ServiceEvent.UNREGISTERING, reference)
self._dispatcher.fire_service_event(event)
# Update the bundle registration information
bundle = reference.get_bundle()
bundle._unregistered_service(registration)
# Remove the unregistering reference
del self.__unregistering_services[reference]
return True
|
def unregister_service(self, registration)
|
Unregisters the given service
:param registration: A ServiceRegistration to the service to unregister
:raise BundleException: Invalid reference
| 4.136935
| 4.335472
| 0.954207
|
with self._lock:
if self._state == Bundle.ACTIVE:
self.stop()
self.start()
|
def update(self)
|
Stops and starts the framework, if the framework is active.
:raise BundleException: Something wrong occurred while stopping or
starting the framework.
| 8.570922
| 4.768551
| 1.797385
|
# type: (Optional[int]) -> bool
if self._state != Bundle.ACTIVE:
# Inactive framework, ignore the call
return True
self._fw_stop_event.wait(timeout)
with self._lock:
# If the timeout raised, we should be in another state
return self._state == Bundle.RESOLVED
|
def wait_for_stop(self, timeout=None)
|
Waits for the framework to stop. Does nothing if the framework bundle
is not in ACTIVE state.
Uses a threading.Condition object
:param timeout: The maximum time to wait (in seconds)
:return: True if the framework has stopped, False if the timeout raised
| 8.391638
| 7.118028
| 1.178927
|
# type: (Any) -> bool
return self.__registry.unget_service(
self.__bundle, self.__reference, service
)
|
def unget_service(self, service)
|
Releases a service object for the associated service.
:param service: An instance of a service returned by ``get_service()``
:return: True if the bundle usage has been removed
| 8.43528
| 14.00403
| 0.602347
|
return self.__framework._dispatcher.add_service_listener(
self, listener, specification, ldap_filter
)
|
def add_service_listener(
self, listener, ldap_filter=None, specification=None
)
|
Registers a service listener
The service listener must have a method with the following prototype::
def service_changed(self, event):
'''
Called by Pelix when some service properties changes
event: A ServiceEvent object
'''
# ...
:param bundle_context: This bundle context
:param listener: The listener to register
:param ldap_filter: Filter that must match the service properties
(optional, None to accept all services)
:param specification: The specification that must provide the service
(optional, None to accept all services)
:return: True if the listener has been successfully registered
| 7.606052
| 13.20085
| 0.576179
|
# type: (Union[Bundle, int]) -> Bundle
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)
|
def get_bundle(self, bundle_id=None)
|
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
| 4.241686
| 4.933907
| 0.859701
|
# type: (Optional[str], Optional[str]) -> Optional[ServiceReference]
result = self.__framework.find_service_references(
clazz, ldap_filter, True
)
try:
return result[0]
except TypeError:
return None
|
def get_service_reference(self, clazz, ldap_filter=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
| 4.205023
| 6.534309
| 0.64353
|
# type: (Optional[str], Optional[str]) -> Optional[List[ServiceReference]]
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
|
def get_service_references(self, clazz, ldap_filter=None)
|
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.
| 3.198047
| 4.365897
| 0.732506
|
# type: (str, bool) -> tuple
return self.__framework.install_package(path, recursive)
|
def install_package(self, path, recursive=False)
|
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
| 7.586584
| 21.175686
| 0.358269
|
# type: (Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration
return self.__framework.register_service(
self.__bundle,
clazz,
service,
properties,
send_event,
factory,
prototype,
)
|
def register_service(
self,
clazz,
service,
properties,
send_event=True,
factory=False,
prototype=False,
)
|
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
| 3.725395
| 5.576505
| 0.668052
|
# type: (ServiceReference) -> bool
# Lose the dependency
return self.__framework._registry.unget_service(
self.__bundle, reference
)
|
def unget_service(self, reference)
|
Disables a reference to the service
:return: True if the bundle was using this reference, else False
| 11.608808
| 17.830256
| 0.651074
|
# type: (Optional[dict]) -> Framework
if cls.__singleton is None:
# Normalize sys.path
normalize_path()
cls.__singleton = Framework(properties)
return cls.__singleton
|
def get_framework(cls, properties=None)
|
If it doesn't exist yet, creates a framework with the given properties,
else returns the current framework instance.
:return: A Pelix instance
| 8.332505
| 12.358466
| 0.674235
|
# type: (Optional[Framework]) -> bool
# pylint: disable=W0212
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
|
def delete_framework(cls, framework=None)
|
Removes the framework singleton
:return: True on success, else False
| 3.132807
| 3.351407
| 0.934774
|
# type: (List[str], Optional[List[str]]) -> Optional[List[str]]
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
|
def get_matching_interfaces(object_class, 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
| 3.396062
| 3.965549
| 0.856391
|
# type: (str, Dict[str, Any], Any) -> Any
if not props:
return default
try:
return props[name]
except KeyError:
return default
|
def get_prop_value(name, props, default=None)
|
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
| 2.49792
| 4.544495
| 0.549659
|
# type: (str, Dict[str, Any], Any) -> None
value = get_prop_value(name, props)
if value is None:
props[name] = if_null
|
def set_prop_if_null(name, props, 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
| 2.783698
| 4.86623
| 0.572044
|
# type: (Any) -> Optional[List[str]]
if value:
if isinstance(value, str):
return [value]
if isinstance(value, list):
return value
if isinstance(value, tuple):
return list(value)
return None
|
def get_string_plus_property_value(value)
|
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
| 2.51577
| 3.077253
| 0.817538
|
# type: (str, Dict[str, Any], Optional[Any]) -> Any
val = get_string_plus_property_value(get_prop_value(name, props, default))
return default if val is None else val
|
def get_string_plus_property(name, props, default=None)
|
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
| 3.528529
| 6.555765
| 0.538233
|
# type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]]
# 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
)
|
def get_exported_interfaces(svc_ref, overriding_props=None)
|
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
| 2.856621
| 3.555022
| 0.803545
|
# type: (List[str], List[str]) -> bool
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
|
def validate_exported_interfaces(object_class, exported_intfs)
|
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
| 2.759139
| 3.407066
| 0.809828
|
# type: (List[str], Dict[str, Any]) -> List[Tuple[str, str]]
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
|
def get_package_versions(intfs, props)
|
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)
| 3.2558
| 3.920547
| 0.830445
|
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
|
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
| 2.794758
| 2.798086
| 0.998811
|
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
|
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
| 2.309189
| 2.29575
| 1.005854
|
# type: (Dict[str, Any]) -> Dict[str, Any]
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_)
}
|
def get_extra_props(props)
|
Returns the extra properties, *i.e.* non-ECF, non-RSA properties
:param props: A dictionary of properties
:return: A filtered dictionary
| 6.556629
| 5.486412
| 1.195067
|
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)
|
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
| 2.330671
| 2.154568
| 1.081735
|
# type: (str, Dict[str, Any], bool) -> Dict[str, Any]
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
|
def get_dot_properties(prefix, props, remove_prefix)
|
Gets the properties starting with the given prefix
| 1.963666
| 2.018492
| 0.972838
|
# type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]
target.update(
{
key: value
for key, value in props.items()
if not is_reserved_property(key)
}
)
return target
|
def copy_non_reserved(props, 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
| 2.200669
| 3.50281
| 0.628258
|
# type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]
target.update(
{key: value for key, value in props.items() if key not in ECFPROPNAMES}
)
return target
|
def copy_non_ecf(props, 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
| 2.922781
| 4.657447
| 0.62755
|
# type: (set, Any) -> set
if item:
if isinstance(item, (list, tuple)):
input_set.update(item)
else:
input_set.add(item)
return input_set
|
def set_append(input_set, item)
|
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
| 2.516371
| 3.627055
| 0.693778
|
# type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent
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(),
)
|
def fromimportreg(cls, bundle, import_reg)
|
Creates a RemoteServiceAdminEvent object from an ImportRegistration
| 2.590893
| 2.261446
| 1.14568
|
# type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent
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(),
)
|
def fromexportreg(cls, bundle, export_reg)
|
Creates a RemoteServiceAdminEvent object from an ExportRegistration
| 2.546676
| 2.202858
| 1.156078
|
# type: (Bundle, ExportRegistration) -> RemoteServiceAdminEvent
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(),
)
|
def fromexportupdate(cls, bundle, export_reg)
|
Creates a RemoteServiceAdminEvent object from the update of an
ExportRegistration
| 2.449213
| 2.149616
| 1.139372
|
# type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent
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(),
)
|
def fromimportupdate(cls, bundle, import_reg)
|
Creates a RemoteServiceAdminEvent object from the update of an
ImportRegistration
| 2.529555
| 2.217298
| 1.140828
|
# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ImportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
return RemoteServiceAdminEvent(
typ=RemoteServiceAdminEvent.IMPORT_UNREGISTRATION,
bundle=bundle,
cid=cid,
rsid=rsid,
import_ref=import_ref,
exception=exception,
endpoint=endpoint,
)
|
def fromimportunreg(
cls, bundle, cid, rsid, import_ref, exception, endpoint
)
|
Creates a RemoteServiceAdminEvent object from the departure of an
ImportRegistration
| 3.35817
| 2.898666
| 1.158522
|
# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ExportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
return RemoteServiceAdminEvent(
typ=RemoteServiceAdminEvent.EXPORT_UNREGISTRATION,
bundle=bundle,
cid=exporterid,
rsid=rsid,
export_ref=export_ref,
exception=exception,
endpoint=endpoint,
)
|
def fromexportunreg(
cls, bundle, exporterid, rsid, export_ref, exception, endpoint
)
|
Creates a RemoteServiceAdminEvent object from the departure of an
ExportRegistration
| 3.775641
| 3.351076
| 1.126695
|
# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.IMPORT_ERROR,
bundle,
importerid,
rsid,
None,
None,
exception,
endpoint,
)
|
def fromimporterror(cls, bundle, importerid, rsid, exception, endpoint)
|
Creates a RemoteServiceAdminEvent object from an import error
| 4.254805
| 3.671416
| 1.1589
|
# type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
return RemoteServiceAdminEvent(
RemoteServiceAdminEvent.EXPORT_ERROR,
bundle,
exporterid,
rsid,
None,
None,
exception,
endpoint,
)
|
def fromexporterror(cls, bundle, exporterid, rsid, exception, endpoint)
|
Creates a RemoteServiceAdminEvent object from an export error
| 4.385797
| 3.665429
| 1.19653
|
# type: (Any, str, str) -> None
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)
|
def _try_instantiate(self, ipopo, factory, component)
|
Tries to instantiate a component from the queue. Hides all exceptions.
:param ipopo: The iPOPO service
:param factory: Component factory
:param component: Component name
| 4.268896
| 4.654321
| 0.91719
|
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)
|
def _start(self)
|
Starts the instantiation queue (called by its bundle activator)
| 9.440373
| 8.525169
| 1.107353
|
# 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
|
def _stop(self)
|
Stops the instantiation queue (called by its bundle activator)
| 9.819207
| 8.244326
| 1.191026
|
self.__names.clear()
self.__queue.clear()
self.__context = None
|
def _clear(self)
|
Clear all references (called by its bundle activator)
| 12.008083
| 9.125
| 1.315954
|
# type: (ServiceEvent) -> None
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)
|
def service_changed(self, event)
|
Handles an event about the iPOPO service
| 7.184907
| 5.960534
| 1.205413
|
# type: (IPopoEvent) -> None
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
|
def handle_ipopo_event(self, event)
|
Handles an iPOPO event
:param event: iPOPO event bean
| 5.685606
| 6.035426
| 0.942039
|
# type: (str, str, dict) -> None
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
|
def add(self, factory, component, properties=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
| 5.064974
| 5.06797
| 0.999409
|
# type: (str) -> None
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
|
def remove(self, component)
|
Kills/Removes the component with the given name
:param component: A component name
:raise KeyError: Unknown component
| 6.51306
| 6.989153
| 0.931881
|
# Set up the request handler creator
active_flag = SharedBoolean(True)
def request_handler(*rh_args):
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
|
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
| 3.572068
| 3.342412
| 1.06871
|
# 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)
|
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
| 3.147543
| 3.049884
| 1.03202
|
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
|
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
| 7.199827
| 7.499205
| 0.960079
|
_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():
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)
|
def handle(self)
|
Handles a TCP client
| 3.81211
| 3.739875
| 1.019315
|
# 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
|
def get_request(self)
|
Accepts a new client. Sets up SSL wrapping if necessary.
:return: A tuple: (client socket, client address tuple)
| 3.252142
| 3.075127
| 1.057563
|
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()
|
def process_request(self, request, client_address)
|
Starts a new thread to process the request, adding the client address
in its name.
| 3.693217
| 3.403336
| 1.085175
|
# type: (str, ShellSession, BundleContext, List[str], int) -> None
# 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()
|
def display_hook(prompt, session, context, matches, longest_match_len)
|
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
| 5.618199
| 5.94315
| 0.945323
|
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
# 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)
]
|
def complete(
self, config, prompt, session, context, current_arguments, 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
| 7.337826
| 8.109385
| 0.904856
|
# type: (str, ShellSession, BundleContext, List[str], int) -> None
# 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()
|
def display_hook(prompt, session, context, matches, longest_match_len)
|
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
| 6.281421
| 6.811136
| 0.922228
|
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
# 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)
]
|
def complete(
self, config, prompt, session, context, current_arguments, 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
| 7.672668
| 8.426725
| 0.910516
|
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
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)
]
|
def complete(
self, config, prompt, session, context, current_arguments, 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
| 3.714745
| 4.143408
| 0.896543
|
return self._handler.headers.get(name, default)
|
def get_header(self, name, default=None)
|
Retrieves the value of a header
| 9.505535
| 9.371655
| 1.014286
|
# Send them all at once
for name, value in self._headers.items():
self._handler.send_header(name, value)
self._handler.end_headers()
|
def end_headers(self)
|
Ends the headers part
| 4.119578
| 4.178271
| 0.985953
|
# pylint: disable=W0221
self._service.log(logging.ERROR, message, *args, **kwargs)
|
def log_error(self, message, *args, **kwargs)
|
Log server error
| 4.81416
| 4.790237
| 1.004994
|
self._service.log(logging.DEBUG, '"%s" %s', self.requestline, code)
|
def log_request(self, code="-", size="-")
|
Logs a request to the server
| 10.962089
| 10.422565
| 1.051765
|
# Use the helper to send the error page
response = _HTTPServletResponse(self)
response.send_content(404, self._service.make_not_found_page(self.path))
|
def send_no_servlet_response(self)
|
Default response sent when no servlet is found for the requested path
| 10.319681
| 10.097523
| 1.022001
|
# 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)
)
|
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
| 5.546956
| 5.506829
| 1.007287
|
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()
|
def server_bind(self)
|
Override server_bind to store the server name, even in IronPython.
See https://ironpython.codeplex.com/workitem/29477
| 3.369906
| 3.559123
| 0.946836
|
# type: (str, Iterable) -> Dict[str, str]
if not list_:
return {}
return {key: " ".join(str(i) for i in list_)}
|
def encode_list(key, 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
| 3.557175
| 4.923288
| 0.72252
|
# type: (str) -> str
if not package:
return ""
lastdot = package.rfind(".")
if lastdot == -1:
return package
return package[:lastdot]
|
def package_name(package)
|
Returns the package name of the given module name
| 3.228674
| 3.347199
| 0.96459
|
# type: (EndpointDescription) -> Dict[str, str]
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
|
def encode_osgi_props(ed)
|
Prepares a dictionary of OSGi properties for the given EndpointDescription
| 2.330689
| 2.329799
| 1.000382
|
# type: (Dict[str, str], str) -> List[str]
val_str = input_props.get(name, None)
if val_str:
return val_str.split(" ")
return []
|
def decode_list(input_props, name)
|
Decodes a space-separated list
| 2.953738
| 2.958149
| 0.998509
|
# type: (Dict[str, Any]) -> Dict[str, Any]
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
|
def decode_osgi_props(input_props)
|
Decodes the OSGi properties of the given endpoint properties
| 2.243706
| 2.223402
| 1.009132
|
# type: (Dict) -> Dict[str, Any]
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
|
def decode_endpoint_props(input_props)
|
Decodes the endpoint properties from the given dictionary
| 2.086761
| 2.091502
| 0.997733
|
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)
|
def encode_endpoint_props(ed)
|
Encodes the properties of the given EndpointDescription
| 2.608444
| 2.603976
| 1.001716
|
# type: (str) -> Tuple[int, int, int]
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
|
def get_package_version(self, package)
|
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)
| 5.777816
| 6.774357
| 0.852895
|
# type: (EndpointDescription) -> bool
return (
self.get_framework_uuid() == endpoint.get_framework_uuid()
and self.get_service_id() == endpoint.get_service_id()
)
|
def is_same_service(self, endpoint)
|
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
| 3.484524
| 3.217936
| 1.082845
|
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)
|
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
| 3.202429
| 3.113571
| 1.028539
|
self.__mqtt.will_set(topic, payload, qos, retain=retain)
|
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
| 3.993083
| 5.610766
| 0.711682
|
# 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()
|
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
| 5.568456
| 5.795924
| 0.960754
|
# 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)
|
def disconnect(self)
|
Disconnects from the MQTT server
| 5.258944
| 4.76182
| 1.104398
|
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]
|
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
| 5.124748
| 5.607149
| 0.913967
|
self.__timer = threading.Timer(delay, self.__reconnect)
self.__timer.daemon = True
self.__timer.start()
|
def __start_timer(self, delay)
|
Starts the reconnection timer
:param delay: Delay (in seconds) before calling the reconnection method
| 3.097854
| 2.630097
| 1.177848
|
# 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)
|
def __reconnect(self)
|
Tries to connect to the MQTT server
| 4.45035
| 4.277054
| 1.040518
|
# pylint: disable=W0613
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)
|
def __on_connect(self, client, userdata, flags, result_code)
|
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)
| 3.571366
| 3.719397
| 0.9602
|
# pylint: disable=W0613
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)
|
def __on_disconnect(self, client, userdata, result_code)
|
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)
| 3.560832
| 3.744399
| 0.950976
|
# pylint: disable=W0613
# 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)
|
def __on_message(self, client, userdata, msg)
|
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
| 3.517038
| 3.868289
| 0.909197
|
# pylint: disable=W0613
try:
self.__in_flight[mid].set()
except KeyError:
pass
|
def __on_publish(self, client, userdata, mid)
|
A message has been published by a server
:param client: Client that received the message
:param userdata: User data (unused)
:param mid: Message ID
| 4.377739
| 6.950458
| 0.629849
|
# type: (dict) -> dict
# 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
|
def to_import_properties(properties)
|
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
| 3.144916
| 3.290761
| 0.955681
|
# type: (pelix.framework.ServiceReference) -> List[str]
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]
|
def compute_exported_specifications(svc_ref)
|
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)
| 2.872245
| 3.017678
| 0.951806
|
# type: (Any[str, List[str]], dict) -> List[str]
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)
|
def extract_specifications(specifications, properties)
|
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)
| 4.328602
| 4.358475
| 0.993146
|
# type: (Iterable[str]) -> List[str]
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)
|
def format_specifications(specifications)
|
Transforms the interfaces names into URI strings, with the interface
implementation language as a scheme.
:param specifications: Specifications to transform
:return: The transformed names
| 4.599059
| 5.356467
| 0.858599
|
# type: (str) -> Tuple[str, str]
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
|
def _extract_specification_parts(specification)
|
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
| 5.799042
| 5.336137
| 1.086749
|
# type: () -> dict
# 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
|
def get_properties(self)
|
Returns merged properties
:return: Endpoint merged properties
| 5.395291
| 5.47785
| 0.984929
|
# type: () -> dict
# 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
|
def make_import_properties(self)
|
Returns the properties of this endpoint where export properties have
been replaced by import ones
:return: A dictionary with import properties
| 14.057942
| 14.825528
| 0.948225
|
# type: (dict) -> None
# 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))
|
def __check_properties(props)
|
Checks that the given dictionary doesn't have export keys and has
import keys
:param props: Properties to validate
:raise ValueError: Invalid properties
| 2.821241
| 2.892669
| 0.975307
|
# type: (str) -> Tuple[int, ...]
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
|
def get_package_version(self, package)
|
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)
| 6.336111
| 7.524585
| 0.842055
|
# type: (Any[str, pelix.ldapfilter.LDAPFilter]) -> bool
return pelix.ldapfilter.get_ldap_filter(ldap_filter).matches(
self.__properties
)
|
def matches(self, ldap_filter)
|
Tests the properties of this EndpointDescription against the given
filter
:param ldap_filter: A filter
:return: True if properties matches the filter
| 8.225801
| 11.672511
| 0.704716
|
# type: () -> ImportEndpoint
# 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,
)
|
def to_import(self)
|
Converts an EndpointDescription bean to an ImportEndpoint
:return: An ImportEndpoint bean
| 5.912265
| 5.684118
| 1.040138
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.