repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
tcalmant/ipopo | pelix/ipopo/decorators.py | get_factory_context | def get_factory_context(cls):
# type: (type) -> FactoryContext
"""
Retrieves the factory context object associated to a factory. Creates it
if needed
:param cls: The factory class
:return: The factory class context
"""
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 | python | def get_factory_context(cls):
# type: (type) -> FactoryContext
"""
Retrieves the factory context object associated to a factory. Creates it
if needed
:param cls: The factory class
:return: The factory class context
"""
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 | Retrieves the factory context object associated to a factory. Creates it
if needed
:param cls: The factory class
:return: The factory class context | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L96-L121 |
tcalmant/ipopo | pelix/ipopo/decorators.py | get_method_description | def get_method_description(method):
# type: (Callable) -> str
"""
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
"""
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__) | python | def get_method_description(method):
# type: (Callable) -> str
"""
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
"""
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__) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L124-L146 |
tcalmant/ipopo | pelix/ipopo/decorators.py | validate_method_arity | def validate_method_arity(method, *needed_args):
# type: (Callable, *str) -> None
"""
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
"""
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),
)
) | python | def validate_method_arity(method, *needed_args):
# type: (Callable, *str) -> None
"""
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
"""
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),
)
) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L149-L196 |
tcalmant/ipopo | pelix/ipopo/decorators.py | _ipopo_setup_callback | def _ipopo_setup_callback(cls, context):
# type: (type, FactoryContext) -> None
"""
Sets up the class _callback dictionary
:param cls: The class to handle
:param context: The factory class context
"""
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) | python | def _ipopo_setup_callback(cls, context):
# type: (type, FactoryContext) -> None
"""
Sets up the class _callback dictionary
:param cls: The class to handle
:param context: The factory class context
"""
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) | Sets up the class _callback dictionary
:param cls: The class to handle
:param context: The factory class context | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L202-L257 |
tcalmant/ipopo | pelix/ipopo/decorators.py | _ipopo_setup_field_callback | def _ipopo_setup_field_callback(cls, context):
# type: (type, FactoryContext) -> None
"""
Sets up the class _field_callback dictionary
:param cls: The class to handle
:param context: The factory class context
"""
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) | python | def _ipopo_setup_field_callback(cls, context):
# type: (type, FactoryContext) -> None
"""
Sets up the class _field_callback dictionary
:param cls: The class to handle
:param context: The factory class context
"""
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) | Sets up the class _field_callback dictionary
:param cls: The class to handle
:param context: The factory class context | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L260-L317 |
tcalmant/ipopo | pelix/ipopo/decorators.py | _append_object_entry | def _append_object_entry(obj, list_name, entry):
# type: (Any, str, Any) -> None
"""
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
"""
# 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) | python | def _append_object_entry(obj, list_name, entry):
# type: (Any, str, Any) -> None
"""
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
"""
# 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) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L335-L357 |
tcalmant/ipopo | pelix/ipopo/decorators.py | _ipopo_class_field_property | def _ipopo_class_field_property(name, value, methods_prefix):
# type: (str, Any, str) -> property
"""
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()
"""
# 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):
"""
Retrieves the property value, from the iPOPO dictionaries
"""
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):
"""
Sets the property value and trigger an update event
:param new_value: The new property 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) | python | def _ipopo_class_field_property(name, value, methods_prefix):
# type: (str, Any, str) -> property
"""
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()
"""
# 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):
"""
Retrieves the property value, from the iPOPO dictionaries
"""
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):
"""
Sets the property value and trigger an update event
:param new_value: The new property 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) | 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() | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L376-L424 |
tcalmant/ipopo | pelix/ipopo/decorators.py | _get_specifications | 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
"""
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__
)
) | python | 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
"""
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__
)
) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L839-L885 |
tcalmant/ipopo | pelix/ipopo/decorators.py | Bind | def Bind(method):
# pylint: disable=C0103
"""
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
"""
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 | python | def Bind(method):
# pylint: disable=C0103
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L1674-L1710 |
tcalmant/ipopo | pelix/ipopo/decorators.py | Update | def Update(method):
# pylint: disable=C0103
"""
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
"""
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 | python | def Update(method):
# pylint: disable=C0103
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L1713-L1750 |
tcalmant/ipopo | pelix/ipopo/decorators.py | Unbind | def Unbind(method):
# pylint: disable=C0103
"""
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
"""
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 | python | def Unbind(method):
# pylint: disable=C0103
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L1753-L1789 |
tcalmant/ipopo | pelix/ipopo/decorators.py | PostRegistration | def PostRegistration(method):
# pylint: disable=C0103
"""
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
"""
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 | python | def PostRegistration(method):
# pylint: disable=C0103
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L1994-L2024 |
tcalmant/ipopo | pelix/ipopo/decorators.py | PostUnregistration | def PostUnregistration(method):
# pylint: disable=C0103
"""
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
"""
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 | python | def PostUnregistration(method):
# pylint: disable=C0103
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L2027-L2057 |
tcalmant/ipopo | pelix/shell/core.py | _ShellUtils.bundlestate_to_str | def bundlestate_to_str(state):
"""
Converts a bundle state integer to a string
"""
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)) | python | def bundlestate_to_str(state):
"""
Converts a bundle state integer to a string
"""
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)) | Converts a bundle state integer to a string | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L80-L93 |
tcalmant/ipopo | pelix/shell/core.py | _ShellUtils.make_table | 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
"""
# 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) | python | 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
"""
# 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) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L96-L180 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.bind_handler | 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
"""
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 | python | 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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L239-L266 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.unbind_handler | 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
"""
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 | python | 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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L268-L289 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.var_set | def var_set(self, session, **kwargs):
"""
Sets the given variables or prints the current ones. "set answer=42"
"""
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) | python | def var_set(self, session, **kwargs):
"""
Sets the given variables or prints the current ones. "set answer=42"
"""
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) | Sets the given variables or prints the current ones. "set answer=42" | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L298-L312 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.bundle_details | def bundle_details(self, io_handler, bundle_id):
"""
Prints the details of the bundle with the given ID or name
"""
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 | python | def bundle_details(self, io_handler, bundle_id):
"""
Prints the details of the bundle with the given ID or name
"""
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 | Prints the details of the bundle with the given ID or name | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L315-L379 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.bundles_list | def bundles_list(self, io_handler, name=None):
"""
Lists the bundles in the framework and their state. Possibility to
filter on the bundle name.
"""
# 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)) | python | def bundles_list(self, io_handler, name=None):
"""
Lists the bundles in the framework and their state. Possibility to
filter on the bundle name.
"""
# 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)) | Lists the bundles in the framework and their state. Possibility to
filter on the bundle name. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L381-L423 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.service_details | def service_details(self, io_handler, service_id):
"""
Prints the details of the service with the given ID
"""
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 | python | def service_details(self, io_handler, service_id):
"""
Prints the details of the service with the given ID
"""
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 | Prints the details of the service with the given ID | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L426-L459 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.services_list | def services_list(self, io_handler, specification=None):
"""
Lists the services in the framework. Possibility to filter on an exact
specification.
"""
# 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 | python | def services_list(self, io_handler, specification=None):
"""
Lists the services in the framework. Possibility to filter on an exact
specification.
"""
# 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 | Lists the services in the framework. Possibility to filter on an exact
specification. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L461-L496 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.properties_list | def properties_list(self, io_handler):
"""
Lists the properties of the framework
"""
# 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)) | python | def properties_list(self, io_handler):
"""
Lists the properties of the framework
"""
# 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)) | Lists the properties of the framework | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L498-L515 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.property_value | def property_value(self, io_handler, name):
"""
Prints the value of the given property, looking into
framework properties then environment variables.
"""
value = self._context.get_property(name)
if value is None:
# Avoid printing "None"
value = ""
io_handler.write_line(str(value)) | python | def property_value(self, io_handler, name):
"""
Prints the value of the given property, looking into
framework properties then environment variables.
"""
value = self._context.get_property(name)
if value is None:
# Avoid printing "None"
value = ""
io_handler.write_line(str(value)) | Prints the value of the given property, looking into
framework properties then environment variables. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L517-L527 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.environment_list | def environment_list(self, io_handler):
"""
Lists the framework process environment variables
"""
# 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)) | python | def environment_list(self, io_handler):
"""
Lists the framework process environment variables
"""
# 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)) | Lists the framework process environment variables | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L529-L543 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.threads_list | def threads_list(io_handler, max_depth=1):
"""
Lists the active threads and their current code line
"""
# 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)) | python | def threads_list(io_handler, max_depth=1):
"""
Lists the active threads and their current code line
"""
# 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)) | Lists the active threads and their current code line | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L553-L616 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.thread_details | def thread_details(io_handler, thread_id, max_depth=0):
"""
Prints details about the thread with the given ID (not its name)
"""
# 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)) | python | def thread_details(io_handler, thread_id, max_depth=0):
"""
Prints details about the thread with the given ID (not its name)
"""
# 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)) | Prints details about the thread with the given ID (not its name) | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L619-L674 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.log_level | def log_level(io_handler, level=None, name=None):
"""
Prints/Changes log level
"""
# 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) | python | def log_level(io_handler, level=None, name=None):
"""
Prints/Changes log level
"""
# 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) | Prints/Changes log level | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L677-L702 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.change_dir | def change_dir(self, session, path):
"""
Changes the working directory
"""
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()) | python | def change_dir(self, session, path):
"""
Changes the working directory
"""
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()) | Changes the working directory | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L704-L721 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.__get_bundle | 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
"""
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) | python | 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
"""
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) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L732-L747 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.start | def start(self, io_handler, bundle_id, *bundles_ids):
"""
Starts the bundles with the given IDs. Stops on first failure.
"""
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 | python | def start(self, io_handler, bundle_id, *bundles_ids):
"""
Starts the bundles with the given IDs. Stops on first failure.
"""
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 | Starts the bundles with the given IDs. Stops on first failure. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L750-L773 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.stop | def stop(self, io_handler, bundle_id, *bundles_ids):
"""
Stops the bundles with the given IDs. Stops on first failure.
"""
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 | python | def stop(self, io_handler, bundle_id, *bundles_ids):
"""
Stops the bundles with the given IDs. Stops on first failure.
"""
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 | Stops the bundles with the given IDs. Stops on first failure. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L776-L792 |
tcalmant/ipopo | pelix/shell/core.py | _ShellService.install | def install(self, io_handler, module_name):
"""
Installs the bundle with the given module name
"""
bundle = self._context.install_bundle(module_name)
io_handler.write_line("Bundle ID: {0}", bundle.get_bundle_id())
return bundle.get_bundle_id() | python | def install(self, io_handler, module_name):
"""
Installs the bundle with the given module name
"""
bundle = self._context.install_bundle(module_name)
io_handler.write_line("Bundle ID: {0}", bundle.get_bundle_id())
return bundle.get_bundle_id() | Installs the bundle with the given module name | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/core.py#L813-L819 |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | _HandlerFactory._prepare_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
"""
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 | python | 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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L59-L111 |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | _HandlerFactory.get_handlers | 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
"""
# 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()
] | python | 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
"""
# 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()
] | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L113-L141 |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | TemporalDependency.clear | def clear(self):
"""
Cleans up the manager. The manager can't be used after this method has
been called
"""
# Cancel timer
self.__cancel_timer()
self.__timer = None
self.__timer_args = None
self.__still_valid = False
self._value = None
super(TemporalDependency, self).clear() | python | def clear(self):
"""
Cleans up the manager. The manager can't be used after this method has
been called
"""
# Cancel timer
self.__cancel_timer()
self.__timer = None
self.__timer_args = None
self.__still_valid = False
self._value = None
super(TemporalDependency, self).clear() | Cleans up the manager. The manager can't be used after this method has
been called | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L275-L287 |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | TemporalDependency.on_service_arrival | def on_service_arrival(self, svc_ref):
"""
Called when a service has been registered in the framework
:param svc_ref: A service reference
"""
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 | python | def on_service_arrival(self, svc_ref):
"""
Called when a service has been registered in the framework
:param svc_ref: A service reference
"""
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 | Called when a service has been registered in the framework
:param svc_ref: A service reference | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L289-L310 |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | TemporalDependency.on_service_departure | def on_service_departure(self, svc_ref):
"""
Called when a service has been unregistered from the framework
:param svc_ref: A service reference
"""
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 | python | def on_service_departure(self, svc_ref):
"""
Called when a service has been unregistered from the framework
:param svc_ref: A service reference
"""
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 | Called when a service has been unregistered from the framework
:param svc_ref: A service reference | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L312-L345 |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | TemporalDependency.__cancel_timer | def __cancel_timer(self):
"""
Cancels the timer, and calls its target method immediately
"""
if self.__timer is not None:
self.__timer.cancel()
self.__unbind_call(True)
self.__timer_args = None
self.__timer = None | python | def __cancel_timer(self):
"""
Cancels the timer, and calls its target method immediately
"""
if self.__timer is not None:
self.__timer.cancel()
self.__unbind_call(True)
self.__timer_args = None
self.__timer = None | Cancels the timer, and calls its target method immediately | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L347-L356 |
tcalmant/ipopo | pelix/ipopo/handlers/temporal.py | TemporalDependency.__unbind_call | def __unbind_call(self, still_valid):
"""
Calls the iPOPO unbind method
"""
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]
) | python | def __unbind_call(self, still_valid):
"""
Calls the iPOPO unbind method
"""
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]
) | Calls the iPOPO unbind method | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/temporal.py#L358-L369 |
tcalmant/ipopo | pelix/remote/transport/jabsorb_rpc.py | _JabsorbRpcServlet.do_POST | def do_POST(self, request, response):
# pylint: disable=C0103
"""
Handle a POST request
:param request: The HTTP request bean
:param response: The HTTP response handler
"""
# 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") | python | def do_POST(self, request, response):
# pylint: disable=C0103
"""
Handle a POST request
:param request: The HTTP request bean
:param response: The HTTP response handler
"""
# 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") | Handle a POST request
:param request: The HTTP request bean
:param response: The HTTP response handler | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/transport/jabsorb_rpc.py#L124-L157 |
tcalmant/ipopo | pelix/http/routing.py | RestDispatcher._rest_dispatch | def _rest_dispatch(self, request, response):
# type: (AbstractHTTPServletRequest, AbstractHTTPServletResponse) -> None
"""
Dispatches the request
:param request: Request bean
:param response: Response bean
"""
# 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) | python | def _rest_dispatch(self, request, response):
# type: (AbstractHTTPServletRequest, AbstractHTTPServletResponse) -> None
"""
Dispatches the request
:param request: Request bean
:param response: Response bean
"""
# 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) | Dispatches the request
:param request: Request bean
:param response: Response bean | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/routing.py#L280-L364 |
tcalmant/ipopo | pelix/http/routing.py | RestDispatcher._setup_rest_dispatcher | def _setup_rest_dispatcher(self):
"""
Finds all methods to call when handling a route
"""
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 | python | def _setup_rest_dispatcher(self):
"""
Finds all methods to call when handling a route
"""
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 | Finds all methods to call when handling a route | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/routing.py#L366-L381 |
tcalmant/ipopo | pelix/http/routing.py | RestDispatcher.__convert_route | def __convert_route(route):
# type: (str) -> Tuple[Pattern[str], Dict[str, Callable[[str], Any]]]
"""
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})
"""
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 | python | def __convert_route(route):
# type: (str) -> Tuple[Pattern[str], Dict[str, Callable[[str], Any]]]
"""
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})
"""
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 | 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}) | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/http/routing.py#L384-L436 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.check_event | def check_event(self, event):
# type: (ServiceEvent) -> bool
"""
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
"""
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) | python | def check_event(self, event):
# type: (ServiceEvent) -> bool
"""
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
"""
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) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L167-L182 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.bind | def bind(self, dependency, svc, svc_ref):
# type: (Any, Any, ServiceReference) -> None
"""
Called by a dependency manager to inject a new service and update the
component life cycle.
"""
with self._lock:
self.__set_binding(dependency, svc, svc_ref)
self.check_lifecycle() | python | def bind(self, dependency, svc, svc_ref):
# type: (Any, Any, ServiceReference) -> None
"""
Called by a dependency manager to inject a new service and update the
component life cycle.
"""
with self._lock:
self.__set_binding(dependency, svc, svc_ref)
self.check_lifecycle() | Called by a dependency manager to inject a new service and update the
component life cycle. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L184-L192 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.update | def update(self, dependency, svc, svc_ref, old_properties, new_value=False):
# type: (Any, Any, ServiceReference, dict, bool) -> None
"""
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
"""
with self._lock:
self.__update_binding(
dependency, svc, svc_ref, old_properties, new_value
)
self.check_lifecycle() | python | def update(self, dependency, svc, svc_ref, old_properties, new_value=False):
# type: (Any, Any, ServiceReference, dict, bool) -> None
"""
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
"""
with self._lock:
self.__update_binding(
dependency, svc, svc_ref, old_properties, new_value
)
self.check_lifecycle() | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L194-L210 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.unbind | def unbind(self, dependency, svc, svc_ref):
# type: (Any, Any, ServiceReference) -> None
"""
Called by a dependency manager to remove an injected service and to
update the component life cycle.
"""
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() | python | def unbind(self, dependency, svc, svc_ref):
# type: (Any, Any, ServiceReference) -> None
"""
Called by a dependency manager to remove an injected service and to
update the component life cycle.
"""
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() | Called by a dependency manager to remove an injected service and to
update the component life cycle. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L212-L227 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.set_controller_state | def set_controller_state(self, name, value):
# type: (str, bool) -> None
"""
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
"""
with self._lock:
self._controllers_state[name] = value
self.__safe_handlers_callback("on_controller_change", name, value) | python | def set_controller_state(self, name, value):
# type: (str, bool) -> None
"""
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
"""
with self._lock:
self._controllers_state[name] = value
self.__safe_handlers_callback("on_controller_change", 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L240-L250 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.update_property | def update_property(self, name, old_value, new_value):
# type: (str, Any, Any) -> None
"""
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
"""
with self._lock:
self.__safe_handlers_callback(
"on_property_change", name, old_value, new_value
) | python | def update_property(self, name, old_value, new_value):
# type: (str, Any, Any) -> None
"""
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
"""
with self._lock:
self.__safe_handlers_callback(
"on_property_change", 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L252-L264 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.update_hidden_property | def update_hidden_property(self, name, old_value, new_value):
# type: (str, Any, Any) -> None
"""
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
"""
with self._lock:
self.__safe_handlers_callback(
"on_hidden_property_change", name, old_value, new_value
) | python | def update_hidden_property(self, name, old_value, new_value):
# type: (str, Any, Any) -> None
"""
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
"""
with self._lock:
self.__safe_handlers_callback(
"on_hidden_property_change", 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L266-L278 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.get_handlers | 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
"""
with self._lock:
if kind is not None:
try:
return self._handlers[kind][:]
except KeyError:
return []
return self.__all_handlers.copy() | python | 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
"""
with self._lock:
if kind is not None:
try:
return self._handlers[kind][:]
except KeyError:
return []
return self.__all_handlers.copy() | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L280-L295 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.check_lifecycle | 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
"""
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) | python | 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
"""
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) | Tests if the state of the component must be updated, based on its own
state and on the state of its dependencies | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L297-L322 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.update_bindings | def update_bindings(self):
# type: () -> bool
"""
Updates the bindings of the given component
:return: True if the component can be validated
"""
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 | python | def update_bindings(self):
# type: () -> bool
"""
Updates the bindings of the given component
:return: True if the component can be validated
"""
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 | Updates the bindings of the given component
:return: True if the component can be validated | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L324-L341 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.retry_erroneous | def retry_erroneous(self, properties_update):
# type: (dict) -> int
"""
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
"""
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 | python | def retry_erroneous(self, properties_update):
# type: (dict) -> int
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L350-L375 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.invalidate | def invalidate(self, callback=True):
# type: (bool) -> bool
"""
Applies the component invalidation.
:param callback: If True, call back the component before the
invalidation
:return: False if the component wasn't valid
"""
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 | python | def invalidate(self, callback=True):
# type: (bool) -> bool
"""
Applies the component invalidation.
:param callback: If True, call back the component before the
invalidation
:return: False if the component wasn't valid
"""
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 | Applies the component invalidation.
:param callback: If True, call back the component before the
invalidation
:return: False if the component wasn't valid | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L377-L413 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.kill | def kill(self):
# type: () -> bool
"""
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
"""
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 | python | def kill(self):
# type: () -> bool
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L415-L475 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.validate | def validate(self, safe_callback=True):
# type: (bool) -> bool
"""
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
"""
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 | python | def validate(self, safe_callback=True):
# type: (bool) -> bool
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L477-L533 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__callback | def __callback(self, event, *args, **kwargs):
# type: (str, *Any, **Any) -> Any
"""
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
"""
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 | python | def __callback(self, event, *args, **kwargs):
# type: (str, *Any, **Any) -> Any
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L535-L555 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__validation_callback | def __validation_callback(self, event):
# type: (str) -> Any
"""
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
"""
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 | python | def __validation_callback(self, event):
# type: (str) -> Any
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L557-L595 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__field_callback | def __field_callback(self, field, event, *args, **kwargs):
# type: (str, str, *Any, **Any) -> Any
"""
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
"""
# 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 | python | def __field_callback(self, field, event, *args, **kwargs):
# type: (str, str, *Any, **Any) -> Any
"""
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
"""
# 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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L597-L626 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.safe_callback | def safe_callback(self, event, *args, **kwargs):
# type: (str, *Any, **Any) -> Any
"""
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
"""
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 | python | def safe_callback(self, event, *args, **kwargs):
# type: (str, *Any, **Any) -> Any
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L628-L665 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__safe_validation_callback | def __safe_validation_callback(self, event):
# type: (str) -> Any
"""
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
"""
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 | python | def __safe_validation_callback(self, event):
# type: (str) -> Any
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L667-L710 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__safe_handler_callback | def __safe_handler_callback(self, handler, method_name, *args, **kwargs):
# type: (Any, str, *Any, **Any) -> Any
"""
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
"""
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 | python | def __safe_handler_callback(self, handler, method_name, *args, **kwargs):
# type: (Any, str, *Any, **Any) -> Any
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L753-L810 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__safe_handlers_callback | def __safe_handlers_callback(self, method_name, *args, **kwargs):
# type: (str, *Any, **Any) -> bool
"""
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
"""
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 | python | def __safe_handlers_callback(self, method_name, *args, **kwargs):
# type: (str, *Any, **Any) -> bool
"""
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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L812-L870 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__set_binding | def __set_binding(self, dependency, service, reference):
# type: (Any, Any, ServiceReference) -> None
"""
Injects a service in the component
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service
"""
# 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,
) | python | def __set_binding(self, dependency, service, reference):
# type: (Any, Any, ServiceReference) -> None
"""
Injects a service in the component
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service
"""
# 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,
) | Injects a service in the component
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L872-L892 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__update_binding | def __update_binding(
self, dependency, service, reference, old_properties, new_value
):
# type: (Any, Any, ServiceReference, dict, bool) -> None
"""
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
"""
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
) | python | def __update_binding(
self, dependency, service, reference, old_properties, new_value
):
# type: (Any, Any, ServiceReference, dict, bool) -> None
"""
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
"""
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
) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L894-L925 |
tcalmant/ipopo | pelix/ipopo/instance.py | StoredInstance.__unset_binding | def __unset_binding(self, dependency, service, reference):
# type: (Any, Any, ServiceReference) -> None
"""
Removes a service from the component
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service
"""
# 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) | python | def __unset_binding(self, dependency, service, reference):
# type: (Any, Any, ServiceReference) -> None
"""
Removes a service from the component
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service
"""
# 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) | Removes a service from the component
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L927-L950 |
tcalmant/ipopo | pelix/misc/eventadmin_printer.py | _parse_boolean | def _parse_boolean(value):
"""
Returns a boolean value corresponding to the given value.
:param value: Any value
:return: Its boolean value
"""
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 | python | def _parse_boolean(value):
"""
Returns a boolean value corresponding to the given value.
:param value: Any value
:return: Its boolean value
"""
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 | Returns a boolean value corresponding to the given value.
:param value: Any value
:return: Its boolean value | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/eventadmin_printer.py#L58-L74 |
tcalmant/ipopo | pelix/ipopo/handlers/requiresvarfilter.py | _VariableFilterMixIn._find_keys | def _find_keys(self):
"""
Looks for the property keys in the filter string
:return: A list of property keys
"""
formatter = string.Formatter()
return [
val[1] for val in formatter.parse(self._original_filter) if val[1]
] | python | def _find_keys(self):
"""
Looks for the property keys in the filter string
:return: A list of property keys
"""
formatter = string.Formatter()
return [
val[1] for val in formatter.parse(self._original_filter) if val[1]
] | Looks for the property keys in the filter string
:return: A list of property keys | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresvarfilter.py#L162-L171 |
tcalmant/ipopo | pelix/ipopo/handlers/requiresvarfilter.py | _VariableFilterMixIn.update_filter | 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
"""
# 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 | python | 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
"""
# 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 | Update the filter according to the new properties
:return: True if the filter changed, else False
:raise ValueError: The filter is invalid | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresvarfilter.py#L173-L210 |
tcalmant/ipopo | pelix/ipopo/handlers/requiresvarfilter.py | _VariableFilterMixIn.on_property_change | def on_property_change(self, name, old_value, new_value):
# pylint: disable=W0613
"""
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
"""
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) | python | def on_property_change(self, name, old_value, new_value):
# pylint: disable=W0613
"""
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
"""
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) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresvarfilter.py#L212-L231 |
tcalmant/ipopo | pelix/ipopo/handlers/requiresvarfilter.py | _VariableFilterMixIn._reset | def _reset(self):
"""
Called when the filter has been changed
"""
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) | python | def _reset(self):
"""
Called when the filter has been changed
"""
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) | Called when the filter has been changed | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresvarfilter.py#L233-L249 |
tcalmant/ipopo | pelix/threadpool.py | EventData.set | def set(self, data=None):
"""
Sets the event
"""
self.__data = data
self.__exception = None
self.__event.set() | python | def set(self, data=None):
"""
Sets the event
"""
self.__data = data
self.__exception = None
self.__event.set() | Sets the event | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L97-L103 |
tcalmant/ipopo | pelix/threadpool.py | EventData.raise_exception | def raise_exception(self, exception):
"""
Raises an exception in wait()
:param exception: An Exception object
"""
self.__data = None
self.__exception = exception
self.__event.set() | python | def raise_exception(self, exception):
"""
Raises an exception in wait()
:param exception: An Exception object
"""
self.__data = None
self.__exception = exception
self.__event.set() | Raises an exception in wait()
:param exception: An Exception object | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L105-L113 |
tcalmant/ipopo | pelix/threadpool.py | EventData.wait | 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
"""
# 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 | python | 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
"""
# 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 | Waits for the event or for the timeout
:param timeout: Wait timeout (in seconds)
:return: True if the event as been set, else False | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L115-L129 |
tcalmant/ipopo | pelix/threadpool.py | FutureResult.__notify | def __notify(self):
"""
Notify the given callback about the result of the execution
"""
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) | python | def __notify(self):
"""
Notify the given callback about the result of the execution
"""
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) | Notify the given callback about the result of the execution | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L153-L165 |
tcalmant/ipopo | pelix/threadpool.py | FutureResult.set_callback | 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
"""
self.__callback = method
self.__extra = extra
if self._done_event.is_set():
# The execution has already finished
self.__notify() | python | 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
"""
self.__callback = method
self.__extra = extra
if self._done_event.is_set():
# The execution has already finished
self.__notify() | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L167-L182 |
tcalmant/ipopo | pelix/threadpool.py | FutureResult.execute | 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
"""
# 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() | python | 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
"""
# 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() | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L184-L213 |
tcalmant/ipopo | pelix/threadpool.py | FutureResult.result | 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
"""
if self._done_event.wait(timeout):
return self._done_event.data
else:
raise OSError("Timeout raised") | python | 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
"""
if self._done_event.wait(timeout):
return self._done_event.data
else:
raise OSError("Timeout raised") | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L221-L233 |
tcalmant/ipopo | pelix/threadpool.py | ThreadPool.start | def start(self):
"""
Starts the thread pool. Does nothing if the pool is already started.
"""
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() | python | def start(self):
"""
Starts the thread pool. Does nothing if the pool is already started.
"""
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() | Starts the thread pool. Does nothing if the pool is already started. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L308-L334 |
tcalmant/ipopo | pelix/threadpool.py | ThreadPool.__start_thread | def __start_thread(self):
"""
Starts a new thread, if possible
"""
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 | python | def __start_thread(self):
"""
Starts a new thread, if possible
"""
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 | Starts a new thread, if possible | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L336-L362 |
tcalmant/ipopo | pelix/threadpool.py | ThreadPool.stop | def stop(self):
"""
Stops the thread pool. Does nothing if the pool is already stopped.
"""
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() | python | def stop(self):
"""
Stops the thread pool. Does nothing if the pool is already stopped.
"""
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() | Stops the thread pool. Does nothing if the pool is already stopped. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L364-L400 |
tcalmant/ipopo | pelix/threadpool.py | ThreadPool.enqueue | 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
"""
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 | python | 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
"""
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 | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L402-L429 |
tcalmant/ipopo | pelix/threadpool.py | ThreadPool.clear | def clear(self):
"""
Empties the current queue content.
Returns once the queue have been emptied.
"""
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() | python | def clear(self):
"""
Empties the current queue content.
Returns once the queue have been emptied.
"""
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() | Empties the current queue content.
Returns once the queue have been emptied. | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L431-L447 |
tcalmant/ipopo | pelix/threadpool.py | ThreadPool.join | 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
"""
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) | python | 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
"""
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) | 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 | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L449-L467 |
tcalmant/ipopo | pelix/threadpool.py | ThreadPool.__run | def __run(self):
"""
The main loop
"""
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 | python | def __run(self):
"""
The main loop
"""
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 | The main loop | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L469-L534 |
cfhamlet/os-docid | src/os_docid/x.py | docid | 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
"""
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) | python | 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
"""
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) | 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 | https://github.com/cfhamlet/os-docid/blob/d3730aa118182f903b540ea738cd47c83f6b5e89/src/os_docid/x.py#L172-L229 |
hasgeek/coaster | coaster/logger.py | init_app | def init_app(app):
"""
Enables logging for an app using :class:`LocalVarFormatter`. Requires the
app to be configured and checks for the following configuration parameters.
All are optional:
* ``LOGFILE``: Name of the file to log to (default ``error.log``)
* ``ADMINS``: List of email addresses of admins who will be mailed error reports
* ``MAIL_DEFAULT_SENDER``: From address of email. Can be an address or a tuple with name and address
* ``MAIL_SERVER``: SMTP server to send with (default ``localhost``)
* ``MAIL_USERNAME`` and ``MAIL_PASSWORD``: SMTP credentials, if required
* ``SLACK_LOGGING_WEBHOOKS``: If present, will send error logs to all specified Slack webhooks
* ``ADMIN_NUMBERS``: List of mobile numbers of admin to send SMS alerts. Requires the following values too
* ``SMS_EXOTEL_SID``: Exotel SID for Indian numbers (+91 prefix)
* ``SMS_EXOTEL_TOKEN``: Exotel token
* ``SMS_EXOTEL_FROM``: Exotel sender's number
* ``SMS_TWILIO_SID``: Twilio SID for non-Indian numbers
* ``SMS_TWILIO_TOKEN``: Twilio token
* ``SMS_TWILIO_FROM``: Twilio sender's number
Format for ``SLACK_LOGGING_WEBHOOKS``::
SLACK_LOGGING_WEBHOOKS = [{
'levelnames': ['WARNING', 'ERROR', 'CRITICAL'],
'url': 'https://hooks.slack.com/...'
}]
"""
formatter = LocalVarFormatter()
error_log_file = app.config.get('LOGFILE', 'error.log')
if error_log_file: # Specify a falsy value in config to disable the log file
file_handler = logging.FileHandler(error_log_file)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
if app.config.get('ADMIN_NUMBERS'):
if all(key in app.config for key in ['SMS_EXOTEL_SID', 'SMS_EXOTEL_TOKEN', 'SMS_EXOTEL_FROM',
'SMS_TWILIO_SID', 'SMS_TWILIO_TOKEN', 'SMS_TWILIO_FROM']):
# A little trickery because directly creating
# an SMSHandler object didn't work
logging.handlers.SMSHandler = SMSHandler
sms_handler = logging.handlers.SMSHandler(
app_name=app.name,
exotel_sid=app.config['SMS_EXOTEL_SID'],
exotel_token=app.config['SMS_EXOTEL_TOKEN'],
exotel_from=app.config['SMS_EXOTEL_FROM'],
twilio_sid=app.config['SMS_TWILIO_SID'],
twilio_token=app.config['SMS_TWILIO_TOKEN'],
twilio_from=app.config['SMS_TWILIO_FROM'],
phonenumbers=app.config['ADMIN_NUMBERS'])
sms_handler.setLevel(logging.ERROR)
app.logger.addHandler(sms_handler)
if app.config.get('SLACK_LOGGING_WEBHOOKS'):
logging.handlers.SlackHandler = SlackHandler
slack_handler = logging.handlers.SlackHandler(
app_name=app.name, webhooks=app.config['SLACK_LOGGING_WEBHOOKS'])
slack_handler.setFormatter(formatter)
slack_handler.setLevel(logging.NOTSET)
app.logger.addHandler(slack_handler)
if app.config.get('ADMINS'):
# MAIL_DEFAULT_SENDER is the new setting for default mail sender in Flask-Mail
# DEFAULT_MAIL_SENDER is the old setting. We look for both
mail_sender = app.config.get('MAIL_DEFAULT_SENDER') or app.config.get(
'DEFAULT_MAIL_SENDER', '[email protected]')
if isinstance(mail_sender, (list, tuple)):
mail_sender = mail_sender[1] # Get email from (name, email)
if app.config.get('MAIL_USERNAME') and app.config.get('MAIL_PASSWORD'):
credentials = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
else:
credentials = None
mail_handler = logging.handlers.SMTPHandler(app.config.get('MAIL_SERVER', 'localhost'),
mail_sender,
app.config['ADMINS'],
'%s failure' % app.name,
credentials=credentials)
mail_handler.setFormatter(formatter)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler) | python | def init_app(app):
"""
Enables logging for an app using :class:`LocalVarFormatter`. Requires the
app to be configured and checks for the following configuration parameters.
All are optional:
* ``LOGFILE``: Name of the file to log to (default ``error.log``)
* ``ADMINS``: List of email addresses of admins who will be mailed error reports
* ``MAIL_DEFAULT_SENDER``: From address of email. Can be an address or a tuple with name and address
* ``MAIL_SERVER``: SMTP server to send with (default ``localhost``)
* ``MAIL_USERNAME`` and ``MAIL_PASSWORD``: SMTP credentials, if required
* ``SLACK_LOGGING_WEBHOOKS``: If present, will send error logs to all specified Slack webhooks
* ``ADMIN_NUMBERS``: List of mobile numbers of admin to send SMS alerts. Requires the following values too
* ``SMS_EXOTEL_SID``: Exotel SID for Indian numbers (+91 prefix)
* ``SMS_EXOTEL_TOKEN``: Exotel token
* ``SMS_EXOTEL_FROM``: Exotel sender's number
* ``SMS_TWILIO_SID``: Twilio SID for non-Indian numbers
* ``SMS_TWILIO_TOKEN``: Twilio token
* ``SMS_TWILIO_FROM``: Twilio sender's number
Format for ``SLACK_LOGGING_WEBHOOKS``::
SLACK_LOGGING_WEBHOOKS = [{
'levelnames': ['WARNING', 'ERROR', 'CRITICAL'],
'url': 'https://hooks.slack.com/...'
}]
"""
formatter = LocalVarFormatter()
error_log_file = app.config.get('LOGFILE', 'error.log')
if error_log_file: # Specify a falsy value in config to disable the log file
file_handler = logging.FileHandler(error_log_file)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
if app.config.get('ADMIN_NUMBERS'):
if all(key in app.config for key in ['SMS_EXOTEL_SID', 'SMS_EXOTEL_TOKEN', 'SMS_EXOTEL_FROM',
'SMS_TWILIO_SID', 'SMS_TWILIO_TOKEN', 'SMS_TWILIO_FROM']):
# A little trickery because directly creating
# an SMSHandler object didn't work
logging.handlers.SMSHandler = SMSHandler
sms_handler = logging.handlers.SMSHandler(
app_name=app.name,
exotel_sid=app.config['SMS_EXOTEL_SID'],
exotel_token=app.config['SMS_EXOTEL_TOKEN'],
exotel_from=app.config['SMS_EXOTEL_FROM'],
twilio_sid=app.config['SMS_TWILIO_SID'],
twilio_token=app.config['SMS_TWILIO_TOKEN'],
twilio_from=app.config['SMS_TWILIO_FROM'],
phonenumbers=app.config['ADMIN_NUMBERS'])
sms_handler.setLevel(logging.ERROR)
app.logger.addHandler(sms_handler)
if app.config.get('SLACK_LOGGING_WEBHOOKS'):
logging.handlers.SlackHandler = SlackHandler
slack_handler = logging.handlers.SlackHandler(
app_name=app.name, webhooks=app.config['SLACK_LOGGING_WEBHOOKS'])
slack_handler.setFormatter(formatter)
slack_handler.setLevel(logging.NOTSET)
app.logger.addHandler(slack_handler)
if app.config.get('ADMINS'):
# MAIL_DEFAULT_SENDER is the new setting for default mail sender in Flask-Mail
# DEFAULT_MAIL_SENDER is the old setting. We look for both
mail_sender = app.config.get('MAIL_DEFAULT_SENDER') or app.config.get(
'DEFAULT_MAIL_SENDER', '[email protected]')
if isinstance(mail_sender, (list, tuple)):
mail_sender = mail_sender[1] # Get email from (name, email)
if app.config.get('MAIL_USERNAME') and app.config.get('MAIL_PASSWORD'):
credentials = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
else:
credentials = None
mail_handler = logging.handlers.SMTPHandler(app.config.get('MAIL_SERVER', 'localhost'),
mail_sender,
app.config['ADMINS'],
'%s failure' % app.name,
credentials=credentials)
mail_handler.setFormatter(formatter)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler) | Enables logging for an app using :class:`LocalVarFormatter`. Requires the
app to be configured and checks for the following configuration parameters.
All are optional:
* ``LOGFILE``: Name of the file to log to (default ``error.log``)
* ``ADMINS``: List of email addresses of admins who will be mailed error reports
* ``MAIL_DEFAULT_SENDER``: From address of email. Can be an address or a tuple with name and address
* ``MAIL_SERVER``: SMTP server to send with (default ``localhost``)
* ``MAIL_USERNAME`` and ``MAIL_PASSWORD``: SMTP credentials, if required
* ``SLACK_LOGGING_WEBHOOKS``: If present, will send error logs to all specified Slack webhooks
* ``ADMIN_NUMBERS``: List of mobile numbers of admin to send SMS alerts. Requires the following values too
* ``SMS_EXOTEL_SID``: Exotel SID for Indian numbers (+91 prefix)
* ``SMS_EXOTEL_TOKEN``: Exotel token
* ``SMS_EXOTEL_FROM``: Exotel sender's number
* ``SMS_TWILIO_SID``: Twilio SID for non-Indian numbers
* ``SMS_TWILIO_TOKEN``: Twilio token
* ``SMS_TWILIO_FROM``: Twilio sender's number
Format for ``SLACK_LOGGING_WEBHOOKS``::
SLACK_LOGGING_WEBHOOKS = [{
'levelnames': ['WARNING', 'ERROR', 'CRITICAL'],
'url': 'https://hooks.slack.com/...'
}] | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/logger.py#L246-L329 |
hasgeek/coaster | coaster/logger.py | LocalVarFormatter.format | 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.
"""
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) | python | 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.
"""
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) | 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. | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/logger.py#L40-L50 |
hasgeek/coaster | coaster/utils/text.py | sanitize_html | def sanitize_html(value, valid_tags=VALID_TAGS, strip=True):
"""
Strips unwanted markup out of HTML.
"""
return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip) | python | def sanitize_html(value, valid_tags=VALID_TAGS, strip=True):
"""
Strips unwanted markup out of HTML.
"""
return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip) | Strips unwanted markup out of HTML. | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/text.py#L61-L65 |
hasgeek/coaster | coaster/utils/text.py | word_count | def word_count(text, html=True):
"""
Return the count of words in the given text. If the text is HTML (default True),
tags are stripped before counting. Handles punctuation and bad formatting like.this
when counting words, but assumes conventions for Latin script languages. May not
be reliable for other languages.
"""
if html:
text = _tag_re.sub(' ', text)
text = _strip_re.sub('', text)
text = _punctuation_re.sub(' ', text)
return len(text.split()) | python | def word_count(text, html=True):
"""
Return the count of words in the given text. If the text is HTML (default True),
tags are stripped before counting. Handles punctuation and bad formatting like.this
when counting words, but assumes conventions for Latin script languages. May not
be reliable for other languages.
"""
if html:
text = _tag_re.sub(' ', text)
text = _strip_re.sub('', text)
text = _punctuation_re.sub(' ', text)
return len(text.split()) | Return the count of words in the given text. If the text is HTML (default True),
tags are stripped before counting. Handles punctuation and bad formatting like.this
when counting words, but assumes conventions for Latin script languages. May not
be reliable for other languages. | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/text.py#L138-L149 |
hasgeek/coaster | coaster/utils/text.py | deobfuscate_email | def deobfuscate_email(text):
"""
Deobfuscate email addresses in provided text
"""
text = unescape(text)
# Find the "dot"
text = _deobfuscate_dot1_re.sub('.', text)
text = _deobfuscate_dot2_re.sub(r'\1.\2', text)
text = _deobfuscate_dot3_re.sub(r'\1.\2', text)
# Find the "at"
text = _deobfuscate_at1_re.sub('@', text)
text = _deobfuscate_at2_re.sub(r'\1@\2', text)
text = _deobfuscate_at3_re.sub(r'\1@\2', text)
return text | python | def deobfuscate_email(text):
"""
Deobfuscate email addresses in provided text
"""
text = unescape(text)
# Find the "dot"
text = _deobfuscate_dot1_re.sub('.', text)
text = _deobfuscate_dot2_re.sub(r'\1.\2', text)
text = _deobfuscate_dot3_re.sub(r'\1.\2', text)
# Find the "at"
text = _deobfuscate_at1_re.sub('@', text)
text = _deobfuscate_at2_re.sub(r'\1@\2', text)
text = _deobfuscate_at3_re.sub(r'\1@\2', text)
return text | Deobfuscate email addresses in provided text | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/text.py#L161-L175 |
hasgeek/coaster | coaster/utils/text.py | simplify_text | def simplify_text(text):
"""
Simplify text to allow comparison.
>>> simplify_text("Awesome Coder wanted at Awesome Company")
'awesome coder wanted at awesome company'
>>> simplify_text("Awesome Coder, wanted at Awesome Company! ")
'awesome coder wanted at awesome company'
>>> simplify_text(u"Awesome Coder, wanted at Awesome Company! ") == 'awesome coder wanted at awesome company'
True
"""
if isinstance(text, six.text_type):
if six.PY3: # pragma: no cover
text = text.translate(text.maketrans("", "", string.punctuation)).lower()
else: # pragma: no cover
text = six.text_type(text.encode('utf-8').translate(string.maketrans("", ""), string.punctuation).lower(), 'utf-8')
else:
text = text.translate(string.maketrans("", ""), string.punctuation).lower()
return " ".join(text.split()) | python | def simplify_text(text):
"""
Simplify text to allow comparison.
>>> simplify_text("Awesome Coder wanted at Awesome Company")
'awesome coder wanted at awesome company'
>>> simplify_text("Awesome Coder, wanted at Awesome Company! ")
'awesome coder wanted at awesome company'
>>> simplify_text(u"Awesome Coder, wanted at Awesome Company! ") == 'awesome coder wanted at awesome company'
True
"""
if isinstance(text, six.text_type):
if six.PY3: # pragma: no cover
text = text.translate(text.maketrans("", "", string.punctuation)).lower()
else: # pragma: no cover
text = six.text_type(text.encode('utf-8').translate(string.maketrans("", ""), string.punctuation).lower(), 'utf-8')
else:
text = text.translate(string.maketrans("", ""), string.punctuation).lower()
return " ".join(text.split()) | Simplify text to allow comparison.
>>> simplify_text("Awesome Coder wanted at Awesome Company")
'awesome coder wanted at awesome company'
>>> simplify_text("Awesome Coder, wanted at Awesome Company! ")
'awesome coder wanted at awesome company'
>>> simplify_text(u"Awesome Coder, wanted at Awesome Company! ") == 'awesome coder wanted at awesome company'
True | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/utils/text.py#L178-L196 |
hasgeek/coaster | coaster/nlp.py | extract_named_entities | def extract_named_entities(text_blocks):
"""
Return a list of named entities extracted from provided text blocks (list of text strings).
"""
sentences = []
for text in text_blocks:
sentences.extend(nltk.sent_tokenize(text))
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True)
def extract_entity_names(t):
entity_names = []
if hasattr(t, 'label'):
if t.label() == 'NE':
entity_names.append(' '.join([child[0] for child in t]))
else:
for child in t:
entity_names.extend(extract_entity_names(child))
return entity_names
entity_names = []
for tree in chunked_sentences:
entity_names.extend(extract_entity_names(tree))
return set(entity_names) | python | def extract_named_entities(text_blocks):
"""
Return a list of named entities extracted from provided text blocks (list of text strings).
"""
sentences = []
for text in text_blocks:
sentences.extend(nltk.sent_tokenize(text))
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True)
def extract_entity_names(t):
entity_names = []
if hasattr(t, 'label'):
if t.label() == 'NE':
entity_names.append(' '.join([child[0] for child in t]))
else:
for child in t:
entity_names.extend(extract_entity_names(child))
return entity_names
entity_names = []
for tree in chunked_sentences:
entity_names.extend(extract_entity_names(tree))
return set(entity_names) | Return a list of named entities extracted from provided text blocks (list of text strings). | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/nlp.py#L20-L48 |
hasgeek/coaster | coaster/manage.py | set_alembic_revision | def set_alembic_revision(path=None):
"""Create/Update alembic table to latest revision number"""
config = Config()
try:
config.set_main_option("script_location", path or "migrations")
script = ScriptDirectory.from_config(config)
head = script.get_current_head()
# create alembic table
metadata, alembic_version = alembic_table_metadata()
metadata.create_all()
item = manager.db.session.query(alembic_version).first()
if item and item.version_num != head:
item.version_num = head
else:
item = alembic_version.insert().values(version_num=head)
item.compile()
conn = manager.db.engine.connect()
conn.execute(item)
manager.db.session.commit()
stdout.write("alembic head is set to %s \n" % head)
except CommandError as e:
stdout.write(e.message) | python | def set_alembic_revision(path=None):
"""Create/Update alembic table to latest revision number"""
config = Config()
try:
config.set_main_option("script_location", path or "migrations")
script = ScriptDirectory.from_config(config)
head = script.get_current_head()
# create alembic table
metadata, alembic_version = alembic_table_metadata()
metadata.create_all()
item = manager.db.session.query(alembic_version).first()
if item and item.version_num != head:
item.version_num = head
else:
item = alembic_version.insert().values(version_num=head)
item.compile()
conn = manager.db.engine.connect()
conn.execute(item)
manager.db.session.commit()
stdout.write("alembic head is set to %s \n" % head)
except CommandError as e:
stdout.write(e.message) | Create/Update alembic table to latest revision number | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L54-L75 |
hasgeek/coaster | coaster/manage.py | dropdb | def dropdb():
"""Drop database tables"""
manager.db.engine.echo = True
if prompt_bool("Are you sure you want to lose all your data"):
manager.db.drop_all()
metadata, alembic_version = alembic_table_metadata()
alembic_version.drop()
manager.db.session.commit() | python | def dropdb():
"""Drop database tables"""
manager.db.engine.echo = True
if prompt_bool("Are you sure you want to lose all your data"):
manager.db.drop_all()
metadata, alembic_version = alembic_table_metadata()
alembic_version.drop()
manager.db.session.commit() | Drop database tables | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L79-L86 |
hasgeek/coaster | coaster/manage.py | createdb | def createdb():
"""Create database tables from sqlalchemy models"""
manager.db.engine.echo = True
manager.db.create_all()
set_alembic_revision() | python | def createdb():
"""Create database tables from sqlalchemy models"""
manager.db.engine.echo = True
manager.db.create_all()
set_alembic_revision() | Create database tables from sqlalchemy models | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L90-L94 |
hasgeek/coaster | coaster/manage.py | sync_resources | def sync_resources():
"""Sync the client's resources with the Lastuser server"""
print("Syncing resources with Lastuser...")
resources = manager.app.lastuser.sync_resources()['results']
for rname, resource in six.iteritems(resources):
if resource['status'] == 'error':
print("Error for %s: %s" % (rname, resource['error']))
else:
print("Resource %s %s..." % (rname, resource['status']))
for aname, action in six.iteritems(resource['actions']):
if action['status'] == 'error':
print("\tError for %s/%s: %s" % (rname, aname, action['error']))
else:
print("\tAction %s/%s %s..." % (rname, aname, resource['status']))
print("Resources synced...") | python | def sync_resources():
"""Sync the client's resources with the Lastuser server"""
print("Syncing resources with Lastuser...")
resources = manager.app.lastuser.sync_resources()['results']
for rname, resource in six.iteritems(resources):
if resource['status'] == 'error':
print("Error for %s: %s" % (rname, resource['error']))
else:
print("Resource %s %s..." % (rname, resource['status']))
for aname, action in six.iteritems(resource['actions']):
if action['status'] == 'error':
print("\tError for %s/%s: %s" % (rname, aname, action['error']))
else:
print("\tAction %s/%s %s..." % (rname, aname, resource['status']))
print("Resources synced...") | Sync the client's resources with the Lastuser server | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L98-L113 |
hasgeek/coaster | coaster/manage.py | init_manager | def init_manager(app, db, **kwargs):
"""
Initialise Manager
:param app: Flask app object
:parm db: db instance
:param kwargs: Additional keyword arguments to be made available as shell context
"""
manager.app = app
manager.db = db
manager.context = kwargs
manager.add_command('db', MigrateCommand)
manager.add_command('clean', Clean())
manager.add_command('showurls', ShowUrls())
manager.add_command('shell', Shell(make_context=shell_context))
manager.add_command('plainshell', Shell(make_context=shell_context,
use_ipython=False, use_bpython=False))
return manager | python | def init_manager(app, db, **kwargs):
"""
Initialise Manager
:param app: Flask app object
:parm db: db instance
:param kwargs: Additional keyword arguments to be made available as shell context
"""
manager.app = app
manager.db = db
manager.context = kwargs
manager.add_command('db', MigrateCommand)
manager.add_command('clean', Clean())
manager.add_command('showurls', ShowUrls())
manager.add_command('shell', Shell(make_context=shell_context))
manager.add_command('plainshell', Shell(make_context=shell_context,
use_ipython=False, use_bpython=False))
return manager | Initialise Manager
:param app: Flask app object
:parm db: db instance
:param kwargs: Additional keyword arguments to be made available as shell context | https://github.com/hasgeek/coaster/blob/07f7eb5d5f516e22fa14fdf4dc70e0ae13ee398d/coaster/manage.py#L122-L139 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.