code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# type: (ExportEndpoint) -> EndpointDescription 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)
def from_export(cls, endpoint)
Converts an ExportEndpoint bean to an EndpointDescription :param endpoint: An ExportEndpoint bean :return: An EndpointDescription bean
2.996789
3.007301
0.996505
# type: (ElementTree.Element) -> EndpointDescription endpoint = {} for prop_node in node.findall(TAG_PROPERTY): name, value = self._parse_property(prop_node) endpoint[name] = value return EndpointDescription(None, endpoint)
def _parse_description(self, node)
Parse an endpoint description node :param node: The endpoint description node :return: The parsed EndpointDescription bean :raise KeyError: Attribute missing :raise ValueError: Invalid description
4.30834
5.2388
0.822391
# type: (ElementTree.Element) -> Tuple[str, Any] # 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
def _parse_property(self, node)
Parses a property node :param node: The property node :return: A (name, value) tuple :raise KeyError: Attribute missing
3.428633
3.945143
0.869077
# type: (str, ElementTree.Element) -> Any 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))
def _parse_value_node(self, vtype, node)
Parses a value node :param vtype: The value type :param node: The value node :return: The parsed value
2.749241
3.323089
0.827315
# type: (str) -> List[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) ]
def parse(self, xml_str)
Parses an EDEF XML string :param xml_str: An XML string :return: The list of parsed EndpointDescription
4.009665
3.908797
1.025805
# type: (ElementTree.Element, EndpointDescription) -> None 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))
def _make_endpoint(self, root_node, endpoint)
Converts the given endpoint bean to an XML Element :param root_node: The XML root Element :param endpoint: An EndpointDescription bean
2.919719
3.059373
0.954352
# type: (List[EndpointDescription]) -> ElementTree.Element root = ElementTree.Element(TAG_ENDPOINT_DESCRIPTIONS) for endpoint in endpoints: self._make_endpoint(root, endpoint) # Prepare pretty-printing self._indent(root) return root
def _make_xml(self, endpoints)
Converts the given endpoint description beans into an XML Element :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document
4.59279
6.245275
0.735402
# type: (List[EndpointDescription]) -> str # 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()
def to_string(self, endpoints)
Converts the given endpoint description beans into a string :param endpoints: A list of EndpointDescription beans :return: A string containing an XML document
5.372619
6.066901
0.885562
# type: (List[EndpointDescription], str) -> None with open(filename, "w") as filep: filep.write(self.to_string(endpoints))
def write(self, endpoints, filename)
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
3.867022
5.72587
0.67536
# type: (type, str, bool) -> bool 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
def is_from_parent(cls, attribute_name, value=None)
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
3.766902
4.070126
0.9255
# type: (type) -> FactoryContext context = getattr(cls, constants.IPOPO_FACTORY_CONTEXT, None) if context is None: # Class not yet manipulated context = FactoryContext() elif is_from_parent(cls, constants.IPOPO_FACTORY_CONTEXT): # Create a copy the context context = context.copy(True) # * Manipulation has not been applied yet context.completed = False else: # Nothing special to do return context # Context has been created or copied, inject the new bean setattr(cls, constants.IPOPO_FACTORY_CONTEXT, context) return context
def get_factory_context(cls)
Retrieves the factory context object associated to a factory. Creates it if needed :param cls: The factory class :return: The factory class context
5.907162
6.570695
0.899016
# type: (Callable) -> str try: try: line_no = inspect.getsourcelines(method)[1] except IOError: # Error reading the source file line_no = -1 return "'{method}' ({file}:{line})".format( method=method.__name__, file=inspect.getfile(method), line=line_no ) except TypeError: # Method can't be inspected return "'{0}'".format(method.__name__)
def get_method_description(method)
Retrieves a description of the given method. If possible, the description contains the source file name and line. :param method: A method :return: A description of the method (at least its name) :raise AttributeError: Given object has no __name__ attribute
3.059719
3.286229
0.931073
# type: (Callable, *str) -> None nb_needed_args = len(needed_args) # Test the number of parameters arg_spec = get_method_arguments(method) method_args = arg_spec.args try: # Remove the self argument when present if method_args[0] == "self": del method_args[0] except IndexError: pass nb_args = len(method_args) if arg_spec.varargs is not None: # Variable arguments if nb_args != 0: # Other arguments detected raise TypeError( "When using '*args', the decorated {0} method must only " "accept the 'self' argument".format( get_method_description(method) ) ) elif arg_spec.keywords is not None: raise TypeError("Methods using '**kwargs' are not handled") elif nb_args != nb_needed_args: # "Normal" arguments raise TypeError( "The decorated method {0} must accept exactly {1} parameters: " "(self, {2})".format( get_method_description(method), nb_needed_args + 1, ", ".join(needed_args), ) )
def validate_method_arity(method, *needed_args)
Tests if the decorated method has a sufficient number of parameters. :param method: The method to be tested :param needed_args: The name (for description only) of the needed arguments, without "self". :return: Nothing :raise TypeError: Invalid number of parameter
3.262647
3.346849
0.974841
# type: (type, FactoryContext) -> None assert inspect.isclass(cls) assert isinstance(context, FactoryContext) if context.callbacks is not None: callbacks = context.callbacks.copy() else: callbacks = {} functions = inspect.getmembers(cls, inspect.isroutine) for _, func in functions: if not hasattr(func, constants.IPOPO_METHOD_CALLBACKS): # No attribute, get the next member continue method_callbacks = getattr(func, constants.IPOPO_METHOD_CALLBACKS) if not isinstance(method_callbacks, list): # Invalid content _logger.warning( "Invalid callback information %s in %s", constants.IPOPO_METHOD_CALLBACKS, get_method_description(func), ) continue # Keeping it allows inheritance : by removing it, only the first # child will see the attribute -> Don't remove it # Store the call backs for _callback in method_callbacks: if _callback in callbacks and not is_from_parent( cls, callbacks[_callback].__name__, callbacks[_callback] ): _logger.warning( "Redefining the callback %s in class '%s'.\n" "\tPrevious callback : %s\n" "\tNew callback : %s", _callback, cls.__name__, get_method_description(callbacks[_callback]), get_method_description(func), ) callbacks[_callback] = func # Update the factory context context.callbacks.clear() context.callbacks.update(callbacks)
def _ipopo_setup_callback(cls, context)
Sets up the class _callback dictionary :param cls: The class to handle :param context: The factory class context
3.925859
4.038322
0.972151
# type: (type, FactoryContext) -> None assert inspect.isclass(cls) assert isinstance(context, FactoryContext) if context.field_callbacks is not None: callbacks = context.field_callbacks.copy() else: callbacks = {} functions = inspect.getmembers(cls, inspect.isroutine) for name, func in functions: if not hasattr(func, constants.IPOPO_METHOD_FIELD_CALLBACKS): # No attribute, get the next member continue method_callbacks = getattr(func, constants.IPOPO_METHOD_FIELD_CALLBACKS) if not isinstance(method_callbacks, list): # Invalid content _logger.warning( "Invalid attribute %s in %s", constants.IPOPO_METHOD_FIELD_CALLBACKS, name, ) continue # Keeping it allows inheritance : by removing it, only the first # child will see the attribute -> Don't remove it # Store the call backs for kind, field, if_valid in method_callbacks: fields_cbs = callbacks.setdefault(field, {}) if kind in fields_cbs and not is_from_parent( cls, fields_cbs[kind][0].__name__ ): _logger.warning( "Redefining the callback %s in '%s'. " "Previous callback : '%s' (%s). " "New callback : %s", kind, name, fields_cbs[kind][0].__name__, fields_cbs[kind][0], func, ) fields_cbs[kind] = (func, if_valid) # Update the factory context context.field_callbacks.clear() context.field_callbacks.update(callbacks)
def _ipopo_setup_field_callback(cls, context)
Sets up the class _field_callback dictionary :param cls: The class to handle :param context: The factory class context
3.884554
4.027936
0.964403
# type: (Any, str, Any) -> None # Get the list obj_list = getattr(obj, list_name, None) if obj_list is None: # We'll have to create it obj_list = [] setattr(obj, list_name, obj_list) assert isinstance(obj_list, list) # Set up the property, if needed if entry not in obj_list: obj_list.append(entry)
def _append_object_entry(obj, list_name, entry)
Appends the given entry in the given object list. Creates the list field if needed. :param obj: The object that contains the list :param list_name: The name of the list member in *obj* :param entry: The entry to be added to the list :raise ValueError: Invalid attribute content
2.732342
3.398192
0.804058
# type: (str, Any, str) -> property # The property lock lock = threading.RLock() # Prepare the methods names getter_name = "{0}{1}".format(methods_prefix, constants.IPOPO_GETTER_SUFFIX) setter_name = "{0}{1}".format(methods_prefix, constants.IPOPO_SETTER_SUFFIX) local_holder = Holder(value) def get_value(self): getter = getattr(self, getter_name, None) if getter is not None: # Use the component getter with lock: return getter(self, name) else: # Use the local holder return local_holder.value def set_value(self, new_value): setter = getattr(self, setter_name, None) if setter is not None: # Use the component setter with lock: setter(self, name, new_value) else: # Change the local holder local_holder.value = new_value return property(get_value, set_value)
def _ipopo_class_field_property(name, value, methods_prefix)
Sets up an iPOPO field property, using Python property() capabilities :param name: The property name :param value: The property default value :param methods_prefix: The common prefix of the getter and setter injected methods :return: A generated Python property()
2.45053
2.638578
0.928731
if not specifications or specifications is object: raise ValueError("No specifications given") elif inspect.isclass(specifications): if Provides.USE_MODULE_QUALNAME: if sys.version_info < (3, 3, 0): raise ValueError( "Qualified name capability requires Python 3.3+" ) # Get the name of the class if not specifications.__module__: return [specifications.__qualname__] return [ "{0}.{1}".format( specifications.__module__, specifications.__qualname__ ) ] else: # Legacy behavior return [specifications.__name__] elif is_string(specifications): # Specification name specifications = specifications.strip() if not specifications: raise ValueError("Empty specification given") return [specifications] elif isinstance(specifications, (list, tuple)): # List given: normalize its content results = [] for specification in specifications: results.extend(_get_specifications(specification)) return results else: raise ValueError( "Unhandled specifications type : {0}".format( type(specifications).__name__ ) )
def _get_specifications(specifications)
Computes the list of strings corresponding to the given specifications :param specifications: A string, a class or a list of specifications :return: A list of strings :raise ValueError: Invalid specification found
3.40743
3.343994
1.01897
# pylint: disable=C0103 if not inspect.isroutine(method): raise TypeError("@Bind can only be applied on functions") # Tests the number of parameters validate_method_arity(method, "service", "service_reference") _append_object_entry( method, constants.IPOPO_METHOD_CALLBACKS, constants.IPOPO_CALLBACK_BIND ) return method
def Bind(method)
The ``@Bind`` callback decorator is called when a component is bound to a dependency. The decorated method must accept the injected service object and its :class:`~pelix.framework.ServiceReference` as arguments:: @Bind def bind_method(self, service, service_reference): ''' service: The injected service instance. service_reference: The injected service ServiceReference ''' # ... If the service is a required one, the bind callback is called **before** the component is validated. The service reference can be stored *if it is released on unbind*. Exceptions raised by a bind callback are ignored. :param method: The decorated method :raise TypeError: The decorated element is not a valid function
8.546082
8.814943
0.969499
# pylint: disable=C0103 if not isinstance(method, types.FunctionType): raise TypeError("@Update can only be applied on functions") # Tests the number of parameters validate_method_arity( method, "service", "service_reference", "old_properties" ) _append_object_entry( method, constants.IPOPO_METHOD_CALLBACKS, constants.IPOPO_CALLBACK_UPDATE, ) return method
def Update(method)
The ``@Update`` callback decorator is called when the properties of an injected service have been modified. The decorated method must accept the injected service object and its :class:`~pelix.framework.ServiceReference` and the previous properties as arguments:: @Update def update_method(self, service, service_reference, old_properties): ''' service: The injected service instance. service_reference: The injected service ServiceReference old_properties: The previous service properties ''' # ... Exceptions raised by an update callback are ignored. :param method: The decorated method :raise TypeError: The decorated element is not a valid function
8.250815
6.566526
1.256496
# pylint: disable=C0103 if not isinstance(method, types.FunctionType): raise TypeError("@Unbind can only be applied on functions") # Tests the number of parameters validate_method_arity(method, "service", "service_reference") _append_object_entry( method, constants.IPOPO_METHOD_CALLBACKS, constants.IPOPO_CALLBACK_UNBIND, ) return method
def Unbind(method)
The ``@Unbind`` callback decorator is called when a component dependency is unbound. The decorated method must accept the injected service object and its :class:`~pelix.framework.ServiceReference` as arguments:: @Unbind def unbind_method(self, service, service_reference): ''' service: The previously injected service instance. service_reference: Its ServiceReference ''' # ... If the service is a required one, the unbind callback is called **after** the component has been invalidated. Exceptions raised by an unbind callback are ignored. :param method: The decorated method :raise TypeError: The decorated element is not a valid function
7.90724
7.760581
1.018898
# pylint: disable=C0103 if not isinstance(method, types.FunctionType): raise TypeError("@PostRegistration can only be applied on functions") # Tests the number of parameters validate_method_arity(method, "service_reference") _append_object_entry( method, constants.IPOPO_METHOD_CALLBACKS, constants.IPOPO_CALLBACK_POST_REGISTRATION, ) return method
def PostRegistration(method)
The service post-registration callback decorator is called after a service of the component has been registered to the framework. The decorated method must accept the :class:`~pelix.framework.ServiceReference` of the registered service as argument:: @PostRegistration def callback_method(self, service_reference): ''' service_reference: The ServiceReference of the provided service ''' # ... :param method: The decorated method :raise TypeError: The decorated element is not a valid function
7.645374
7.219228
1.059029
# pylint: disable=C0103 if not isinstance(method, types.FunctionType): raise TypeError("@PostUnregistration can only be applied on functions") # Tests the number of parameters validate_method_arity(method, "service_reference") _append_object_entry( method, constants.IPOPO_METHOD_CALLBACKS, constants.IPOPO_CALLBACK_POST_UNREGISTRATION, ) return method
def PostUnregistration(method)
The service post-unregistration callback decorator is called after a service of the component has been unregistered from the framework. The decorated method must accept the :class:`~pelix.framework.ServiceReference` of the registered service as argument:: @PostUnregistration def callback_method(self, service_reference): ''' service_reference: The ServiceReference of the provided service ''' # ... :param method: The decorated method :raise TypeError: The decorated element is not a valid function
7.346143
6.853119
1.071942
states = { pelix.Bundle.INSTALLED: "INSTALLED", pelix.Bundle.ACTIVE: "ACTIVE", pelix.Bundle.RESOLVED: "RESOLVED", pelix.Bundle.STARTING: "STARTING", pelix.Bundle.STOPPING: "STOPPING", pelix.Bundle.UNINSTALLED: "UNINSTALLED", } return states.get(state, "Unknown state ({0})".format(state))
def bundlestate_to_str(state)
Converts a bundle state integer to a string
2.07497
1.978122
1.04896
# Normalize the prefix prefix = str(prefix or "") # Maximum lengths lengths = [len(title) for title in headers] # Store the number of columns (0-based) nb_columns = len(lengths) - 1 # Lines str_lines = [] for idx, line in enumerate(lines): # Recompute lengths str_line = [] str_lines.append(str_line) column = -1 try: for column, entry in enumerate(line): str_entry = str(entry) str_line.append(str_entry) if len(str_entry) > lengths[column]: lengths[column] = len(str_entry) except IndexError: # Line too small/big raise ValueError( "Different sizes for header and lines " "(line {0})".format(idx + 1) ) except (TypeError, AttributeError): # Invalid type of line raise ValueError( "Invalid type of line: %s", type(line).__name__ ) else: if column != nb_columns: # Check if all lines have the same number of columns raise ValueError( "Different sizes for header and lines " "(line {0})".format(idx + 1) ) # Prepare the head (centered text) format_str = "{0}|".format(prefix) for column, length in enumerate(lengths): format_str += " {%d:^%d} |" % (column, length) head_str = format_str.format(*headers) # Prepare the separator, according the length of the headers string separator = "{0}{1}".format(prefix, "-" * (len(head_str) - len(prefix))) idx = head_str.find("|") while idx != -1: separator = "+".join((separator[:idx], separator[idx + 1 :])) idx = head_str.find("|", idx + 1) # Prepare the output output = [separator, head_str, separator.replace("-", "=")] # Compute the lines format_str = format_str.replace("^", "<") for line in str_lines: output.append(format_str.format(*line)) output.append(separator) # Force the last end of line output.append("") # Join'em return "\n".join(output)
def make_table(headers, lines, prefix=None)
Generates an ASCII table according to the given headers and lines :param headers: List of table headers (N-tuple) :param lines: List of table lines (N-tuples) :param prefix: Optional prefix for each line :return: The ASCII representation of the table :raise ValueError: Different number of columns between headers and lines
3.280839
3.261831
1.005827
if svc_ref in self._bound_references: # Already bound service return False # Get the service handler = self._context.get_service(svc_ref) # Get its name space namespace = handler.get_namespace() commands = [] # Register all service methods directly for command, method in handler.get_methods(): self.register_command(namespace, command, method) commands.append(command) # Store the reference self._bound_references[svc_ref] = handler self._reference_commands[svc_ref] = (namespace, commands) return True
def bind_handler(self, svc_ref)
Called if a command service has been found. Registers the methods of this service. :param svc_ref: A reference to the found service :return: True if the commands have been registered
3.945237
4.010014
0.983846
if svc_ref not in self._bound_references: # Unknown reference return False # Unregister its commands namespace, commands = self._reference_commands[svc_ref] for command in commands: self.unregister(namespace, command) # Release the service self._context.unget_service(svc_ref) del self._bound_references[svc_ref] del self._reference_commands[svc_ref] return True
def unbind_handler(self, svc_ref)
Called if a command service is gone. Unregisters its commands. :param svc_ref: A reference to the unbound service :return: True if the commands have been unregistered
3.576097
3.548484
1.007782
if not kwargs: session.write_line( self._utils.make_table( ("Name", "Value"), session.variables.items() ) ) else: for name, value in kwargs.items(): name = name.strip() session.set(name, value) session.write_line("{0}={1}", name, value)
def var_set(self, session, **kwargs)
Sets the given variables or prints the current ones. "set answer=42"
4.426096
3.709345
1.193228
bundle = None try: # Convert the given ID into an integer bundle_id = int(bundle_id) except ValueError: # Not an integer, suppose it's a bundle name for bundle in self._context.get_bundles(): if bundle.get_symbolic_name() == bundle_id: break else: # Bundle not found bundle = None else: # Integer ID: direct access try: bundle = self._context.get_bundle(bundle_id) except constants.BundleException: pass if bundle is None: # No matching bundle io_handler.write_line("Unknown bundle ID: {0}", bundle_id) return False lines = [ "ID......: {0}".format(bundle.get_bundle_id()), "Name....: {0}".format(bundle.get_symbolic_name()), "Version.: {0}".format(bundle.get_version()), "State...: {0}".format( self._utils.bundlestate_to_str(bundle.get_state()) ), "Location: {0}".format(bundle.get_location()), "Published services:", ] try: services = bundle.get_registered_services() if services: for svc_ref in services: lines.append("\t{0}".format(svc_ref)) else: lines.append("\tn/a") except constants.BundleException as ex: # Bundle in a invalid state lines.append("\tError: {0}".format(ex)) lines.append("Services used by this bundle:") try: services = bundle.get_services_in_use() if services: for svc_ref in services: lines.append("\t{0}".format(svc_ref)) else: lines.append("\tn/a") except constants.BundleException as ex: # Bundle in a invalid state lines.append("\tError: {0}".format(ex)) lines.append("") io_handler.write("\n".join(lines)) return None
def bundle_details(self, io_handler, bundle_id)
Prints the details of the bundle with the given ID or name
2.244285
2.224118
1.009067
# Head of the table headers = ("ID", "Name", "State", "Version") # Get the bundles bundles = self._context.get_bundles() # The framework is not in the result of get_bundles() bundles.insert(0, self._context.get_framework()) if name is not None: # Filter the list bundles = [ bundle for bundle in bundles if name in bundle.get_symbolic_name() ] # Make the entries lines = [ [ str(entry) for entry in ( bundle.get_bundle_id(), bundle.get_symbolic_name(), self._utils.bundlestate_to_str(bundle.get_state()), bundle.get_version(), ) ] for bundle in bundles ] # Print'em all io_handler.write(self._utils.make_table(headers, lines)) if name is None: io_handler.write_line("{0} bundles installed", len(lines)) else: io_handler.write_line("{0} filtered bundles", len(lines))
def bundles_list(self, io_handler, name=None)
Lists the bundles in the framework and their state. Possibility to filter on the bundle name.
3.395652
3.363281
1.009625
svc_ref = self._context.get_service_reference( None, "({0}={1})".format(constants.SERVICE_ID, service_id) ) if svc_ref is None: io_handler.write_line("Service not found: {0}", service_id) return False lines = [ "ID............: {0}".format( svc_ref.get_property(constants.SERVICE_ID) ), "Rank..........: {0}".format( svc_ref.get_property(constants.SERVICE_RANKING) ), "Specifications: {0}".format( svc_ref.get_property(constants.OBJECTCLASS) ), "Bundle........: {0}".format(svc_ref.get_bundle()), "Properties....:", ] for key, value in sorted(svc_ref.get_properties().items()): lines.append("\t{0} = {1}".format(key, value)) lines.append("Bundles using this service:") for bundle in svc_ref.get_using_bundles(): lines.append("\t{0}".format(bundle)) lines.append("") io_handler.write("\n".join(lines)) return None
def service_details(self, io_handler, service_id)
Prints the details of the service with the given ID
2.176093
2.152823
1.010809
# Head of the table headers = ("ID", "Specifications", "Bundle", "Ranking") # Lines references = ( self._context.get_all_service_references(specification, None) or [] ) # Construct the list of services lines = [ [ str(entry) for entry in ( ref.get_property(constants.SERVICE_ID), ref.get_property(constants.OBJECTCLASS), ref.get_bundle(), ref.get_property(constants.SERVICE_RANKING), ) ] for ref in references ] if not lines and specification: # No matching service found io_handler.write_line("No service provides '{0}'", specification) return False # Print'em all io_handler.write(self._utils.make_table(headers, lines)) io_handler.write_line("{0} services registered", len(lines)) return None
def services_list(self, io_handler, specification=None)
Lists the services in the framework. Possibility to filter on an exact specification.
4.410649
4.333559
1.017789
# Get the framework framework = self._context.get_framework() # Head of the table headers = ("Property Name", "Value") # Lines lines = [item for item in framework.get_properties().items()] # Sort lines lines.sort() # Print the table io_handler.write(self._utils.make_table(headers, lines))
def properties_list(self, io_handler)
Lists the properties of the framework
5.458512
5.073151
1.075961
value = self._context.get_property(name) if value is None: # Avoid printing "None" value = "" io_handler.write_line(str(value))
def property_value(self, io_handler, name)
Prints the value of the given property, looking into framework properties then environment variables.
5.331622
4.803357
1.109978
# Head of the table headers = ("Environment Variable", "Value") # Lines lines = [item for item in os.environ.items()] # Sort lines lines.sort() # Print the table io_handler.write(self._utils.make_table(headers, lines))
def environment_list(self, io_handler)
Lists the framework process environment variables
6.54842
5.753609
1.138141
# Normalize maximum depth try: max_depth = int(max_depth) if max_depth < 1: max_depth = None except (ValueError, TypeError): max_depth = None # pylint: disable=W0212 try: # Extract frames frames = sys._current_frames() # Get the thread ID -> Thread mapping names = threading._active.copy() except AttributeError: io_handler.write_line("sys._current_frames() is not available.") return # Sort by thread ID thread_ids = sorted(frames.keys()) lines = [] for thread_id in thread_ids: # Get the corresponding stack stack = frames[thread_id] # Try to get the thread name try: name = names[thread_id].name except KeyError: name = "<unknown>" # Construct the code position lines.append("Thread ID: {0} - Name: {1}".format(thread_id, name)) lines.append("Stack Trace:") trace_lines = [] depth = 0 frame = stack while frame is not None and ( max_depth is None or depth < max_depth ): # Store the line information trace_lines.append(format_frame_info(frame)) # Previous frame... frame = frame.f_back depth += 1 # Reverse the lines trace_lines.reverse() # Add them to the printed lines lines.extend(trace_lines) lines.append("") lines.append("") # Sort the lines io_handler.write("\n".join(lines))
def threads_list(io_handler, max_depth=1)
Lists the active threads and their current code line
2.979328
2.911352
1.023348
# Normalize maximum depth try: max_depth = int(max_depth) if max_depth < 1: max_depth = None except (ValueError, TypeError): max_depth = None # pylint: disable=W0212 try: # Get the stack thread_id = int(thread_id) stack = sys._current_frames()[thread_id] except KeyError: io_handler.write_line("Unknown thread ID: {0}", thread_id) except ValueError: io_handler.write_line("Invalid thread ID: {0}", thread_id) except AttributeError: io_handler.write_line("sys._current_frames() is not available.") else: # Get the name try: name = threading._active[thread_id].name except KeyError: name = "<unknown>" lines = [ "Thread ID: {0} - Name: {1}".format(thread_id, name), "Stack trace:", ] trace_lines = [] depth = 0 frame = stack while frame is not None and ( max_depth is None or depth < max_depth ): # Store the line information trace_lines.append(format_frame_info(frame)) # Previous frame... frame = frame.f_back depth += 1 # Reverse the lines trace_lines.reverse() # Add them to the printed lines lines.extend(trace_lines) lines.append("") io_handler.write("\n".join(lines))
def thread_details(io_handler, thread_id, max_depth=0)
Prints details about the thread with the given ID (not its name)
2.500731
2.491432
1.003732
# Get the logger logger = logging.getLogger(name) # Normalize the name if not name: name = "Root" if not level: # Level not given: print the logger level io_handler.write_line( "{0} log level: {1} (real: {2})", name, logging.getLevelName(logger.getEffectiveLevel()), logging.getLevelName(logger.level), ) else: # Set the logger level try: logger.setLevel(level.upper()) io_handler.write_line("New level for {0}: {1}", name, level) except ValueError: io_handler.write_line("Invalid log level: {0}", level)
def log_level(io_handler, level=None, name=None)
Prints/Changes log level
2.896904
2.757829
1.050429
if path == "-": # Previous directory path = self._previous_path or "." try: previous = os.getcwd() os.chdir(path) except IOError as ex: # Can't change directory session.write_line("Error changing directory: {0}", ex) else: # Store previous path self._previous_path = previous session.write_line(os.getcwd())
def change_dir(self, session, path)
Changes the working directory
4.457405
4.415625
1.009462
try: bundle_id = int(bundle_id) return self._context.get_bundle(bundle_id) except (TypeError, ValueError): io_handler.write_line("Invalid bundle ID: {0}", bundle_id) except constants.BundleException: io_handler.write_line("Unknown bundle: {0}", bundle_id)
def __get_bundle(self, io_handler, bundle_id)
Retrieves the Bundle object with the given bundle ID. Writes errors through the I/O handler if any. :param io_handler: I/O Handler :param bundle_id: String or integer bundle ID :return: The Bundle object matching the given ID, None if not found
3.181617
3.171725
1.003119
for bid in (bundle_id,) + bundles_ids: try: # Got an int => it's a bundle ID bid = int(bid) except ValueError: # Got something else, we will try to install it first bid = self.install(io_handler, bid) bundle = self.__get_bundle(io_handler, bid) if bundle is not None: io_handler.write_line( "Starting bundle {0} ({1})...", bid, bundle.get_symbolic_name(), ) bundle.start() else: return False return None
def start(self, io_handler, bundle_id, *bundles_ids)
Starts the bundles with the given IDs. Stops on first failure.
3.982248
3.997913
0.996082
for bid in (bundle_id,) + bundles_ids: bundle = self.__get_bundle(io_handler, bid) if bundle is not None: io_handler.write_line( "Stopping bundle {0} ({1})...", bid, bundle.get_symbolic_name(), ) bundle.stop() else: return False return None
def stop(self, io_handler, bundle_id, *bundles_ids)
Stops the bundles with the given IDs. Stops on first failure.
3.561026
3.472406
1.025521
bundle = self._context.install_bundle(module_name) io_handler.write_line("Bundle ID: {0}", bundle.get_bundle_id()) return bundle.get_bundle_id()
def install(self, io_handler, module_name)
Installs the bundle with the given module name
4.353471
3.996793
1.089241
if not isinstance(requires_filters, dict): requires_filters = {} if not isinstance(temporal_timeouts, dict): temporal_timeouts = {} if not requires_filters and not temporal_timeouts: # No explicit configuration given return configs # We need to change a part of the requirements new_configs = {} for field, config in configs.items(): # Extract values from tuple requirement, timeout = config explicit_filter = requires_filters.get(field) explicit_timeout = temporal_timeouts.get(field) # Convert the timeout value try: explicit_timeout = int(explicit_timeout) if explicit_timeout <= 0: explicit_timeout = timeout except (ValueError, TypeError): explicit_timeout = timeout if not explicit_filter and not explicit_timeout: # Nothing to do new_configs[field] = config else: try: # Store an updated copy of the requirement requirement_copy = requirement.copy() if explicit_filter: requirement_copy.set_filter(explicit_filter) new_configs[field] = (requirement_copy, explicit_timeout) except (TypeError, ValueError): # No information for this one, or invalid filter: # keep the factory requirement new_configs[field] = config return new_configs
def _prepare_configs(configs, requires_filters, temporal_timeouts)
Overrides the filters specified in the decorator with the given ones :param configs: Field → (Requirement, key, allow_none) dictionary :param requires_filters: Content of the 'requires.filter' component property (field → string) :param temporal_timeouts: Content of the 'temporal.timeouts' component property (field → float) :return: The new configuration dictionary
3.026349
2.946151
1.027221
# Extract information from the context configs = component_context.get_handler( ipopo_constants.HANDLER_TEMPORAL ) requires_filters = component_context.properties.get( ipopo_constants.IPOPO_REQUIRES_FILTERS, None ) temporal_timeouts = component_context.properties.get( ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None ) # Prepare requirements new_configs = self._prepare_configs( configs, requires_filters, temporal_timeouts ) # Return handlers return [ TemporalDependency(field, requirement, timeout) for field, (requirement, timeout) in new_configs.items() ]
def get_handlers(self, component_context, instance)
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component
4.58064
4.804683
0.95337
# Cancel timer self.__cancel_timer() self.__timer = None self.__timer_args = None self.__still_valid = False self._value = None super(TemporalDependency, self).clear()
def clear(self)
Cleans up the manager. The manager can't be used after this method has been called
10.088049
10.306648
0.97879
with self._lock: if self.reference is None: # Inject the service service = self._context.get_service(svc_ref) self.reference = svc_ref self._value.set_service(service) self.__still_valid = True # Cancel timer self.__cancel_timer() # Bind the service self._ipopo_instance.bind(self, self._value, self.reference) return True return None
def on_service_arrival(self, svc_ref)
Called when a service has been registered in the framework :param svc_ref: A service reference
6.110288
6.850502
0.891947
with self._lock: if svc_ref is self.reference: # Forget about the service self._value.unset_service() # Clear the reference self.reference = None # Look for a replacement self._pending_ref = self._context.get_service_reference( self.requirement.specification, self.requirement.filter ) if self._pending_ref is None: # No replacement found yet, wait a little self.__still_valid = True self.__timer_args = (self._value, svc_ref) self.__timer = threading.Timer( self.__timeout, self.__unbind_call, (False,) ) self.__timer.start() else: # Notify iPOPO immediately self._ipopo_instance.unbind(self, self._value, svc_ref) return True return None
def on_service_departure(self, svc_ref)
Called when a service has been unregistered from the framework :param svc_ref: A service reference
6.14657
6.818448
0.901462
if self.__timer is not None: self.__timer.cancel() self.__unbind_call(True) self.__timer_args = None self.__timer = None
def __cancel_timer(self)
Cancels the timer, and calls its target method immediately
6.011561
5.299574
1.134348
with self._lock: if self.__timer is not None: # Timeout expired, we're not valid anymore self.__timer = None self.__still_valid = still_valid self._ipopo_instance.unbind( self, self.__timer_args[0], self.__timer_args[1] )
def __unbind_call(self, still_valid)
Calls the iPOPO unbind method
5.106646
4.278018
1.193694
# pylint: disable=C0103 # Get the request JSON content data = jsonrpclib.loads(to_str(request.read_data())) # Convert from Jabsorb data = jabsorb.from_jabsorb(data) # Dispatch try: result = self._unmarshaled_dispatch(data, self._simple_dispatch) except NoMulticallResult: # No result (never happens, but who knows...) result = None if result is not None: # Convert result to Jabsorb if "result" in result: result["result"] = jabsorb.to_jabsorb(result["result"]) # Store JSON result = jsonrpclib.jdumps(result) else: # It was a notification result = "" # Send the result response.send_content(200, result, "application/json-rpc")
def do_POST(self, request, response)
Handle a POST request :param request: The HTTP request bean :param response: The HTTP response handler
4.637986
4.796747
0.966902
# type: (AbstractHTTPServletRequest, AbstractHTTPServletResponse) -> None # Extract request information http_verb = request.get_command() sub_path = request.get_sub_path() # Find the best matching method, according to the number of # readable arguments max_valid_args = -1 best_method = None best_args = None best_match = None for route, method in self.__routes.get(http_verb, {}).items(): # Parse the request path match = route.match(sub_path) if not match: continue # Count the number of valid arguments method_args = self.__methods_args[method] nb_valid_args = 0 for name in method_args: try: match.group(name) nb_valid_args += 1 except IndexError: # Argument not found pass if nb_valid_args > max_valid_args: # Found a better match max_valid_args = nb_valid_args best_method = method best_args = method_args best_match = match if best_method is None: # No match: return a 404 plain text error response.send_content( 404, "No method to handle path {0}".format(sub_path), "text/plain", ) else: # Found a method # ... convert arguments kwargs = {} if best_args: for name, converter in best_args.items(): try: str_value = best_match.group(name) except IndexError: # Argument is missing: do nothing pass else: if str_value: # Keep the default value when an argument is # missing, i.e. don't give it in kwargs if converter is not None: # Convert the argument kwargs[name] = converter(str_value) else: # Use the string value as is kwargs[name] = str_value # Prepare positional arguments extra_pos_args = [] if kwargs: # Ignore the first two parameters (request and response) method_args = get_method_arguments(best_method).args[:2] for pos_arg in method_args: try: extra_pos_args.append(kwargs.pop(pos_arg)) except KeyError: pass # ... call the method (exceptions will be handled by the server) best_method(request, response, *extra_pos_args, **kwargs)
def _rest_dispatch(self, request, response)
Dispatches the request :param request: Request bean :param response: Response bean
3.16137
3.218374
0.982288
for _, method in inspect.getmembers(self, inspect.isroutine): try: config = getattr(method, HTTP_ROUTE_ATTRIBUTE) except AttributeError: # Not a REST method continue for route in config["routes"]: pattern, arguments = self.__convert_route(route) self.__methods_args.setdefault(method, {}).update(arguments) for http_verb in config["methods"]: self.__routes.setdefault(http_verb, {})[pattern] = method
def _setup_rest_dispatcher(self)
Finds all methods to call when handling a route
4.782985
4.346686
1.100375
# type: (str) -> Tuple[Pattern[str], Dict[str, Callable[[str], Any]]] arguments = {} # type: Dict[str, Callable[[str], Any]] last_idx = 0 final_pattern = [] match_iter = _MARKER_PATTERN.finditer(route) for match_pattern in match_iter: # Copy intermediate string final_pattern.append(route[last_idx : match_pattern.start()]) last_idx = match_pattern.end() + 1 # Extract type declaration match_type = _TYPED_MARKER_PATTERN.match(match_pattern.group()) if not match_type: raise ValueError( "Invalid argument declaration: {0}".format( match_pattern.group() ) ) name, kind = match_type.groups() if kind: kind = kind.lower() # Choose a pattern for each type (can raise a KeyError) regex = TYPE_PATTERNS[kind] # Keep track of argument name and converter arguments[name] = TYPE_CONVERTERS.get(kind) # Generate the regex pattern for this part final_pattern.append("((?P<") final_pattern.append(match_type.group(1)) final_pattern.append(">") final_pattern.append(regex) final_pattern.append(")/?)?") # Copy trailing string final_pattern.append(route[last_idx:]) # Ensure we don't accept trailing values final_pattern.append("$") return re.compile("".join(final_pattern)), arguments
def __convert_route(route)
Converts a route pattern into a regex. The result is a tuple containing the regex pattern to match and a dictionary associating arguments names and their converter (if any) A route can be: "/hello/<name>/<age:int>" :param route: A route string, i.e. a path with type markers :return: A tuple (pattern, {argument name: converter})
3.512443
3.365849
1.043553
# type: (ServiceEvent) -> bool with self._lock: if self.state == StoredInstance.KILLED: # This call may have been blocked by the internal state lock, # ignore it return False return self.__safe_handlers_callback("check_event", event)
def check_event(self, event)
Tests if the given service event must be handled or ignored, based on the state of the iPOPO service and on the content of the event. :param event: A service event :return: True if the event can be handled, False if it must be ignored
13.533804
13.665184
0.990386
# type: (Any, Any, ServiceReference) -> None with self._lock: self.__set_binding(dependency, svc, svc_ref) self.check_lifecycle()
def bind(self, dependency, svc, svc_ref)
Called by a dependency manager to inject a new service and update the component life cycle.
5.331689
5.23271
1.018915
# type: (Any, Any, ServiceReference, dict, bool) -> None with self._lock: self.__update_binding( dependency, svc, svc_ref, old_properties, new_value ) self.check_lifecycle()
def update(self, dependency, svc, svc_ref, old_properties, new_value=False)
Called by a dependency manager when the properties of an injected dependency have been updated. :param dependency: The dependency handler :param svc: The injected service :param svc_ref: The reference of the injected service :param old_properties: Previous properties of the dependency :param new_value: If True, inject the new value of the handler
4.632922
7.673109
0.603787
# type: (Any, Any, ServiceReference) -> None with self._lock: # Invalidate first (if needed) self.check_lifecycle() # Call unbind() and remove the injection self.__unset_binding(dependency, svc, svc_ref) # Try a new configuration if self.update_bindings(): self.check_lifecycle()
def unbind(self, dependency, svc, svc_ref)
Called by a dependency manager to remove an injected service and to update the component life cycle.
8.75852
7.907031
1.107688
# type: (str, bool) -> None with self._lock: self._controllers_state[name] = value self.__safe_handlers_callback("on_controller_change", name, value)
def set_controller_state(self, name, value)
Sets the state of the controller with the given name :param name: The name of the controller :param value: The new value of the controller
5.365284
9.300046
0.576909
# type: (str, Any, Any) -> None with self._lock: self.__safe_handlers_callback( "on_property_change", name, old_value, new_value )
def update_property(self, name, old_value, new_value)
Handles a property changed event :param name: The changed property name :param old_value: The previous property value :param new_value: The new property value
5.20697
7.349869
0.708444
# type: (str, Any, Any) -> None with self._lock: self.__safe_handlers_callback( "on_hidden_property_change", name, old_value, new_value )
def update_hidden_property(self, name, old_value, new_value)
Handles an hidden property changed event :param name: The changed property name :param old_value: The previous property value :param new_value: The new property value
4.983067
7.580613
0.657344
with self._lock: if kind is not None: try: return self._handlers[kind][:] except KeyError: return [] return self.__all_handlers.copy()
def get_handlers(self, kind=None)
Retrieves the handlers of the given kind. If kind is None, all handlers are returned. :param kind: The kind of the handlers to return :return: A list of handlers, or an empty list
4.352099
6.20232
0.701689
with self._lock: # Validation flags was_valid = self.state == StoredInstance.VALID can_validate = self.state not in ( StoredInstance.VALIDATING, StoredInstance.VALID, ) # Test the validity of all handlers handlers_valid = self.__safe_handlers_callback( "is_valid", break_on_false=True ) if was_valid and not handlers_valid: # A dependency is missing self.invalidate(True) elif ( can_validate and handlers_valid and self._ipopo_service.running ): # We're all good self.validate(True)
def check_lifecycle(self)
Tests if the state of the component must be updated, based on its own state and on the state of its dependencies
7.181755
6.857825
1.047235
# type: () -> bool with self._lock: all_valid = True for handler in self.get_handlers(handlers_const.KIND_DEPENDENCY): # Try to bind self.__safe_handler_callback(handler, "try_binding") # Update the validity flag all_valid &= self.__safe_handler_callback( handler, "is_valid", only_boolean=True, none_as_true=True ) return all_valid
def update_bindings(self)
Updates the bindings of the given component :return: True if the component can be validated
8.039683
8.789843
0.914656
# type: (dict) -> int with self._lock: if self.state != StoredInstance.ERRONEOUS: # Not in erroneous state: ignore return self.state # Update properties if properties_update: self.context.properties.update(properties_update) # Reset state self.state = StoredInstance.INVALID self.error_trace = None # Retry self.check_lifecycle() # Check if the component is still erroneous return self.state
def retry_erroneous(self, properties_update)
Removes the ERRONEOUS state from a component and retries a validation :param properties_update: A dictionary to update component properties :return: The new state of the component
5.469012
5.41349
1.010256
# type: (bool) -> bool with self._lock: if self.state != StoredInstance.VALID: # Instance is not running... return False # Change the state self.state = StoredInstance.INVALID # Call the handlers self.__safe_handlers_callback("pre_invalidate") # Call the component if callback: # pylint: disable=W0212 self.__safe_validation_callback( constants.IPOPO_CALLBACK_INVALIDATE ) # Trigger an "Invalidated" event self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.INVALIDATED, self.factory_name, self.name, ) # Call the handlers self.__safe_handlers_callback("post_invalidate") return True
def invalidate(self, callback=True)
Applies the component invalidation. :param callback: If True, call back the component before the invalidation :return: False if the component wasn't valid
5.639233
5.995256
0.940616
# type: () -> bool with self._lock: # Already dead... if self.state == StoredInstance.KILLED: return False try: self.invalidate(True) except: self._logger.exception( "%s: Error invalidating the instance", self.name ) # Now that we are nearly clean, be sure we were in a good registry # state assert not self._ipopo_service.is_registered_instance(self.name) # Stop all handlers (can tell to unset a binding) for handler in self.get_handlers(): results = self.__safe_handler_callback(handler, "stop") if results: try: for binding in results: self.__unset_binding( handler, binding[0], binding[1] ) except Exception as ex: self._logger.exception( "Error stopping handler '%s': %s", handler, ex ) # Call the handlers self.__safe_handlers_callback("clear") # Change the state self.state = StoredInstance.KILLED # Trigger the event # pylint: disable=W0212 self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.KILLED, self.factory_name, self.name ) # Clean up members self._handlers.clear() self.__all_handlers.clear() self._handlers = None self.__all_handlers = None self.context = None self.instance = None self._ipopo_service = None return True
def kill(self)
This instance is killed : invalidate it if needed, clean up all members When this method is called, this StoredInstance object must have been removed from the registry :return: True if the component has been killed, False if it already was
4.979939
4.83707
1.029536
# type: (bool) -> bool with self._lock: if self.state in ( StoredInstance.VALID, StoredInstance.VALIDATING, StoredInstance.ERRONEOUS, ): # No work to do (yet) return False if self.state == StoredInstance.KILLED: raise RuntimeError("{0}: Zombies !".format(self.name)) # Clear the error trace self.error_trace = None # Call the handlers self.__safe_handlers_callback("pre_validate") if safe_callback: # Safe call back needed and not yet passed self.state = StoredInstance.VALIDATING # Call @ValidateComponent first, then @Validate if not self.__safe_validation_callback( constants.IPOPO_CALLBACK_VALIDATE ): # Stop there if the callback failed self.state = StoredInstance.VALID self.invalidate(True) # Consider the component has erroneous self.state = StoredInstance.ERRONEOUS return False # All good self.state = StoredInstance.VALID # Call the handlers self.__safe_handlers_callback("post_validate") # We may have caused a framework error, so check if iPOPO is active if self._ipopo_service is not None: # pylint: disable=W0212 # Trigger the iPOPO event (after the service _registration) self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.VALIDATED, self.factory_name, self.name ) return True
def validate(self, safe_callback=True)
Ends the component validation, registering services :param safe_callback: If True, calls the component validation callback :return: True if the component has been validated, else False :raise RuntimeError: You try to awake a dead component
5.860417
5.876755
0.99722
# type: (str, *Any, **Any) -> Any comp_callback = self.context.get_callback(event) if not comp_callback: # No registered callback return True # Call it result = comp_callback(self.instance, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
def __callback(self, event, *args, **kwargs)
Calls the registered method in the component for the given event :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong
5.105889
6.190251
0.824827
# type: (str) -> Any comp_callback = self.context.get_callback(event) if not comp_callback: # No registered callback return True # Get the list of arguments try: args = getattr(comp_callback, constants.IPOPO_VALIDATE_ARGS) except AttributeError: raise TypeError( "@ValidateComponent callback is missing internal description" ) # Associate values to arguments mapping = { constants.ARG_BUNDLE_CONTEXT: self.bundle_context, constants.ARG_COMPONENT_CONTEXT: self.context, constants.ARG_PROPERTIES: self.context.properties.copy(), } mapped_args = [mapping[arg] for arg in args] # Call it result = comp_callback(self.instance, *mapped_args) if result is None: # Special case, if the call back returns nothing return True return result
def __validation_callback(self, event)
Specific handling for the ``@ValidateComponent`` and ``@InvalidateComponent`` callback, as it requires checking arguments count and order :param event: The kind of life-cycle callback (in/validation) :return: The callback result, or None :raise Exception: Something went wrong
5.460968
5.300649
1.030245
# type: (str, str, *Any, **Any) -> Any # Get the field callback info cb_info = self.context.get_field_callback(field, event) if not cb_info: # No registered callback return True # Extract information callback, if_valid = cb_info if if_valid and self.state != StoredInstance.VALID: # Don't call the method if the component state isn't satisfying return True # Call it result = callback(self.instance, field, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
def __field_callback(self, field, event, *args, **kwargs)
Calls the registered method in the component for the given field event :param field: A field name :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong
5.716385
5.937277
0.962796
# type: (str, *Any, **Any) -> Any if self.state == StoredInstance.KILLED: # Invalid state return None try: return self.__callback(event, *args, **kwargs) except FrameworkException as ex: # Important error self._logger.exception( "Critical error calling back %s: %s", self.name, ex ) # Kill the component self._ipopo_service.kill(self.name) if ex.needs_stop: # Framework must be stopped... self._logger.error( "%s said that the Framework must be stopped.", self.name ) self.bundle_context.get_framework().stop() return False except: self._logger.exception( "Component '%s': error calling callback method for event %s", self.name, event, ) return False
def safe_callback(self, event, *args, **kwargs)
Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None
5.50919
5.64483
0.975971
# type: (str) -> Any if self.state == StoredInstance.KILLED: # Invalid state return None try: return self.__validation_callback(event) except FrameworkException as ex: # Important error self._logger.exception( "Critical error calling back %s: %s", self.name, ex ) # Kill the component self._ipopo_service.kill(self.name) # Store the exception as it is a validation error self.error_trace = traceback.format_exc() if ex.needs_stop: # Framework must be stopped... self._logger.error( "%s said that the Framework must be stopped.", self.name ) self.bundle_context.get_framework().stop() return False except: self._logger.exception( "Component '%s': error calling @ValidateComponent callback", self.name, ) # Store the exception as it is a validation error self.error_trace = traceback.format_exc() return False
def __safe_validation_callback(self, event)
Calls the ``@ValidateComponent`` or ``@InvalidateComponent`` callback, ignoring raised exceptions :param event: The kind of life-cycle callback (in/validation) :return: The callback result, or None
5.874792
5.764462
1.01914
# type: (Any, str, *Any, **Any) -> Any if handler is None or method_name is None: return None # Behavior flags only_boolean = kwargs.pop("only_boolean", False) none_as_true = kwargs.pop("none_as_true", False) # Get the method for each handler try: method = getattr(handler, method_name) except AttributeError: # Method not found result = None else: try: # Call it result = method(*args, **kwargs) except Exception as ex: # No result result = None # Log error self._logger.exception( "Error calling handler '%s': %s", handler, ex ) if result is None and none_as_true: # Consider None (nothing returned) as True result = True if only_boolean: # Convert to a boolean result return bool(result) return result
def __safe_handler_callback(self, handler, method_name, *args, **kwargs)
Calls the given method with the given arguments in the given handler. Logs exceptions, but doesn't propagate them. Special arguments can be given in kwargs: * 'none_as_true': If set to True and the method returned None or doesn't exist, the result is considered as True. If set to False, None result is kept as is. Default is False. * 'only_boolean': If True, the result can only be True or False, else the result is the value returned by the method. Default is False. :param handler: The handler to call :param method_name: The name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and to control the call :return: The method result, or None on error
3.140098
2.938435
1.068629
# type: (str, *Any, **Any) -> bool if self.state == StoredInstance.KILLED: # Nothing to do return False # Behavior flags exception_as_error = kwargs.pop("exception_as_error", False) break_on_false = kwargs.pop("break_on_false", False) result = True for handler in self.get_handlers(): # Get the method for each handler try: method = getattr(handler, method_name) except AttributeError: # Ignore missing methods pass else: try: # Call it res = method(*args, **kwargs) if res is not None and not res: # Ignore 'None' results result = False except Exception as ex: # Log errors self._logger.exception( "Error calling handler '%s': %s", handler, ex ) # We can consider exceptions as errors or ignore them result = result and not exception_as_error if not handler and break_on_false: # The loop can stop here break return result
def __safe_handlers_callback(self, method_name, *args, **kwargs)
Calls the given method with the given arguments in all handlers. Logs exceptions, but doesn't propagate them. Methods called in handlers must return None, True or False. Special parameters can be given in kwargs: * 'exception_as_error': if it is set to True and an exception is raised by a handler, then this method will return False. By default, this flag is set to False and exceptions are ignored. * 'break_on_false': if it set to True, the loop calling the handler will stop after an handler returned False. By default, this flag is set to False, and all handlers are called. :param method_name: Name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and the behavior of the call :return: True if all handlers returned True (or None), else False
4.210737
3.734386
1.127558
# type: (Any, Any, ServiceReference) -> None # Set the value setattr(self.instance, dependency.get_field(), dependency.get_value()) # Call the component back self.safe_callback(constants.IPOPO_CALLBACK_BIND, service, reference) self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_BIND_FIELD, service, reference, )
def __set_binding(self, dependency, service, reference)
Injects a service in the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service
6.310238
8.16135
0.773186
# type: (Any, Any, ServiceReference, dict, bool) -> None if new_value: # Set the value setattr( self.instance, dependency.get_field(), dependency.get_value() ) # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UPDATE_FIELD, service, reference, old_properties, ) self.safe_callback( constants.IPOPO_CALLBACK_UPDATE, service, reference, old_properties )
def __update_binding( self, dependency, service, reference, old_properties, new_value )
Calls back component binding and field binding methods when the properties of an injected dependency have been updated. :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service :param old_properties: Previous properties of the dependency :param new_value: If True, inject the new value of the handler
5.311953
5.139286
1.033597
# type: (Any, Any, ServiceReference) -> None # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UNBIND_FIELD, service, reference, ) self.safe_callback(constants.IPOPO_CALLBACK_UNBIND, service, reference) # Update the injected field setattr(self.instance, dependency.get_field(), dependency.get_value()) # Unget the service self.bundle_context.unget_service(reference)
def __unset_binding(self, dependency, service, reference)
Removes a service from the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service
5.814037
6.629481
0.876997
if not value: return False try: # Lower string to check known "false" value value = value.lower() return value not in ("none", "0", "false", "no") except AttributeError: # Not a string, but has a value return True
def _parse_boolean(value)
Returns a boolean value corresponding to the given value. :param value: Any value :return: Its boolean value
6.398297
7.206885
0.887803
formatter = string.Formatter() return [ val[1] for val in formatter.parse(self._original_filter) if val[1] ]
def _find_keys(self)
Looks for the property keys in the filter string :return: A list of property keys
7.901054
7.795102
1.013592
# Consider the filter invalid self.valid_filter = False try: # Format the new filter filter_str = self._original_filter.format( **self._component_context.properties ) except KeyError as ex: # An entry is missing: abandon logging.warning("Missing filter value: %s", ex) raise ValueError("Missing filter value") try: # Parse the new LDAP filter new_filter = ldapfilter.get_ldap_filter(filter_str) except (TypeError, ValueError) as ex: logging.warning("Error parsing filter: %s", ex) raise ValueError("Error parsing filter") # The filter is valid self.valid_filter = True # Compare to the "old" one if new_filter != self.requirement.filter: # Replace the requirement filter self.requirement.filter = new_filter return True # Same filter return False
def update_filter(self)
Update the filter according to the new properties :return: True if the filter changed, else False :raise ValueError: The filter is invalid
4.698424
4.530523
1.03706
# pylint: disable=W0613 if name in self._keys: try: if self.update_filter(): # This is a key for the filter and the filter has changed # => Force the handler to update its dependency self._reset() except ValueError: # Invalid filter: clear all references, this will invalidate # the component for svc_ref in self.get_bindings(): self.on_service_departure(svc_ref)
def on_property_change(self, name, old_value, new_value)
A component property has been updated :param name: Name of the property :param old_value: Previous value of the property :param new_value: New value of the property
9.47753
10.511215
0.901659
with self._lock: # Start listening to services with the new filter self.stop() self.start() for svc_ref in self.get_bindings(): # Check if the current reference matches the filter if not self.requirement.filter.matches( svc_ref.get_properties() ): # Not the case: emulate a service departure # The instance life cycle will be updated as well self.on_service_departure(svc_ref)
def _reset(self)
Called when the filter has been changed
9.231913
8.5212
1.083405
self.__data = data self.__exception = None self.__event.set()
def set(self, data=None)
Sets the event
10.118506
9.343308
1.082968
self.__data = None self.__exception = exception self.__event.set()
def raise_exception(self, exception)
Raises an exception in wait() :param exception: An Exception object
7.588844
9.787472
0.775363
# The 'or' part is for Python 2.6 result = self.__event.wait(timeout) # pylint: disable=E0702 # Pylint seems to miss the "is None" check below if self.__exception is None: return result else: raise self.__exception
def wait(self, timeout=None)
Waits for the event or for the timeout :param timeout: Wait timeout (in seconds) :return: True if the event as been set, else False
6.164673
6.27505
0.98241
if self.__callback is not None: try: self.__callback( self._done_event.data, self._done_event.exception, self.__extra, ) except Exception as ex: self._logger.exception("Error calling back method: %s", ex)
def __notify(self)
Notify the given callback about the result of the execution
5.053258
4.714098
1.071946
self.__callback = method self.__extra = extra if self._done_event.is_set(): # The execution has already finished self.__notify()
def set_callback(self, method, extra=None)
Sets a callback method, called once the result has been computed or in case of exception. The callback method must have the following signature: ``callback(result, exception, extra)``. :param method: The method to call back in the end of the execution :param extra: Extra parameter to be given to the callback method
7.396791
7.662979
0.965263
# Normalize arguments if args is None: args = [] if kwargs is None: kwargs = {} try: # Call the method result = method(*args, **kwargs) except Exception as ex: # Something went wrong: propagate to the event and to the caller self._done_event.raise_exception(ex) raise else: # Store the result self._done_event.set(result) finally: # In any case: notify the call back (if any) self.__notify()
def execute(self, method, args, kwargs)
Execute the given method and stores its result. The result is considered "done" even if the method raises an exception :param method: The method to execute :param args: Method positional arguments :param kwargs: Method keyword arguments :raise Exception: The exception raised by the method
4.12811
3.980738
1.037021
if self._done_event.wait(timeout): return self._done_event.data else: raise OSError("Timeout raised")
def result(self, timeout=None)
Waits up to timeout for the result the threaded job. Returns immediately the result if the job has already been done. :param timeout: The maximum time to wait for a result (in seconds) :raise OSError: The timeout raised before the job finished :raise Exception: The exception encountered during the call, if any
7.226124
6.248502
1.156457
if not self._done_event.is_set(): # Stop event not set: we're running return # Clear the stop event self._done_event.clear() # Compute the number of threads to start to handle pending tasks nb_pending_tasks = self._queue.qsize() if nb_pending_tasks > self._max_threads: nb_threads = self._max_threads nb_pending_tasks = self._max_threads elif nb_pending_tasks < self._min_threads: nb_threads = self._min_threads else: nb_threads = nb_pending_tasks # Create the threads for _ in range(nb_pending_tasks): self.__nb_pending_task += 1 self.__start_thread() for _ in range(nb_threads - nb_pending_tasks): self.__start_thread()
def start(self)
Starts the thread pool. Does nothing if the pool is already started.
2.849825
2.685611
1.061146
with self.__lock: if self.__nb_threads >= self._max_threads: # Can't create more threads return False if self._done_event.is_set(): # We're stopped: do nothing return False # Prepare thread and start it name = "{0}-{1}".format(self._logger.name, self._thread_id) self._thread_id += 1 thread = threading.Thread(target=self.__run, name=name) thread.daemon = True try: self.__nb_threads += 1 thread.start() self._threads.append(thread) return True except (RuntimeError, OSError): self.__nb_threads -= 1 return False
def __start_thread(self)
Starts a new thread, if possible
3.206816
3.051627
1.050855
if self._done_event.is_set(): # Stop event set: we're stopped return # Set the stop event self._done_event.set() with self.__lock: # Add something in the queue (to unlock the join()) try: for _ in self._threads: self._queue.put(self._done_event, True, self._timeout) except queue.Full: # There is already something in the queue pass # Copy the list of threads to wait for threads = self._threads[:] # Join threads outside the lock for thread in threads: while thread.is_alive(): # Wait 3 seconds thread.join(3) if thread.is_alive(): # Thread is still alive: something might be wrong self._logger.warning( "Thread %s is still alive...", thread.name ) # Clear storage del self._threads[:] self.clear()
def stop(self)
Stops the thread pool. Does nothing if the pool is already stopped.
4.515344
4.313747
1.046734
if not hasattr(method, "__call__"): raise ValueError( "{0} has no __call__ member.".format(method.__name__) ) # Prepare the future result object future = FutureResult(self._logger) # Use a lock, as we might be "resetting" the queue with self.__lock: # Add the task to the queue self._queue.put((method, args, kwargs, future), True, self._timeout) self.__nb_pending_task += 1 if self.__nb_pending_task > self.__nb_threads: # All threads are taken: start a new one self.__start_thread() return future
def enqueue(self, method, *args, **kwargs)
Queues a task in the pool :param method: Method to call :return: A FutureResult object, to get the result of the task :raise ValueError: Invalid method :raise Full: The task queue is full
4.511264
4.18858
1.077039
with self.__lock: # Empty the current queue try: while True: self._queue.get_nowait() self._queue.task_done() except queue.Empty: # Queue is now empty pass # Wait for the tasks currently executed self.join()
def clear(self)
Empties the current queue content. Returns once the queue have been emptied.
4.970848
4.56109
1.089838
if self._queue.empty(): # Nothing to wait for... return True elif timeout is None: # Use the original join self._queue.join() return True else: # Wait for the condition with self._queue.all_tasks_done: self._queue.all_tasks_done.wait(timeout) return not bool(self._queue.unfinished_tasks)
def join(self, timeout=None)
Waits for all the tasks to be executed :param timeout: Maximum time to wait (in seconds) :return: True if the queue has been emptied, else False
3.495356
3.391699
1.030562
already_cleaned = False try: while not self._done_event.is_set(): try: # Wait for an action (blocking) task = self._queue.get(True, self._timeout) if task is self._done_event: # Stop event in the queue: get out self._queue.task_done() return except queue.Empty: # Nothing to do yet pass else: with self.__lock: self.__nb_active_threads += 1 # Extract elements method, args, kwargs, future = task try: # Call the method future.execute(method, args, kwargs) except Exception as ex: self._logger.exception( "Error executing %s: %s", method.__name__, ex ) finally: # Mark the action as executed self._queue.task_done() # Thread is not active anymore with self.__lock: self.__nb_pending_task -= 1 self.__nb_active_threads -= 1 # Clean up thread if necessary with self.__lock: extra_threads = self.__nb_threads - self.__nb_active_threads if ( self.__nb_threads > self._min_threads and extra_threads > self._queue.qsize() ): # No more work for this thread # if there are more non active_thread than task # and we're above the minimum number of threads: # stop this one self.__nb_threads -= 1 # To avoid a race condition: decrease the number of # threads here and mark it as already accounted for already_cleaned = True return finally: # Always clean up with self.__lock: # Thread stops: clean up references try: self._threads.remove(threading.current_thread()) except ValueError: pass if not already_cleaned: self.__nb_threads -= 1
def __run(self)
The main loop
4.365304
4.255781
1.025735
if not isinstance(url, bytes): url = url.encode(encoding) parser = _URL_PARSER idx = 0 for _c in url: if _c not in _HEX: if not (_c == _SYM_MINUS and (idx == _DOMAINID_LENGTH or idx == _HOSTID_LENGTH + 1)): return parser.parse(url, idx) idx += 1 if idx > 4: break _l = len(url) if _l == _DOCID_LENGTH: parser = _DOCID_PARSER elif _l == _READABLE_DOCID_LENGTH \ and url[_DOMAINID_LENGTH] == _SYM_MINUS \ and url[_HOSTID_LENGTH + 1] == _SYM_MINUS: parser = _R_DOCID_PARSER else: parser = _PARSER return parser.parse(url, idx)
def docid(url, encoding='ascii')
Get DocID from URL. DocID generation depends on bytes of the URL string. So, if non-ascii charactors in the URL, encoding should be considered properly. Args: url (str or bytes): Pre-encoded bytes or string will be encoded with the 'encoding' argument. encoding (str, optional): Defaults to 'ascii'. Used to encode url argument if it is not pre-encoded into bytes. Returns: DocID: The DocID object. Examples: >>> from os_docid import docid >>> docid('http://www.google.com/') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8ed646a3334ca891fff90821feeb2b02a33a6f9fc8e5f3fcd') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('abc') NotImplementedError: Not supported data format
4.099371
4.152299
0.987253
if record.exc_info: if record.exc_text: if "Stack frames (most recent call first)" not in record.exc_text: record.exc_text = None return super(LocalVarFormatter, self).format(record)
def format(self, record)
Format the specified record as text. Overrides :meth:`logging.Formatter.format` to remove cache of :attr:`record.exc_text` unless it was produced by this formatter.
4.425233
4.410347
1.003375
return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip)
def sanitize_html(value, valid_tags=VALID_TAGS, strip=True)
Strips unwanted markup out of HTML.
3.144118
3.07946
1.020997