code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
# Store the stored instance
self._ipopo_instance = stored_instance
# Public flags to generate (True for public accessors)
flags_to_generate = set()
if stored_instance.context.properties:
flags_to_generate.add(True)
# (False for hidden ones)
if stored_instance.context.has_hidden_properties():
flags_to_generate.add(False)
# Inject properties getters and setters
for public_flag in flags_to_generate:
# Prepare methods
getter, setter = self._field_property_generator(public_flag)
# Inject the getter and setter at the instance level
getter_name, setter_name = self.get_methods_names(public_flag)
setattr(component_instance, getter_name, getter)
setattr(component_instance, setter_name, setter)
|
def manipulate(self, stored_instance, component_instance)
|
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
| 4.786159
| 4.709577
| 1.016261
|
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__
return module + "." + obj.__class__.__name__
|
def _full_class_name(obj)
|
Returns the full name of the class of the given object
:param obj: Any Python object
:return: The full name of the class of the object (if possible)
| 1.923578
| 2.363708
| 0.813797
|
if prompt:
# Print the prompt
self.write(prompt)
self.output.flush()
# Read the line
return to_str(self.input.readline())
|
def _prompt(self, prompt=None)
|
Reads a line written by the user
:param prompt: An optional prompt message
:return: The read line, after a conversion to str
| 6.35043
| 6.984248
| 0.90925
|
with self.__lock:
self.output.write(to_bytes(data, self.encoding))
|
def _write_bytes(self, data)
|
Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()``
| 7.317892
| 6.563219
| 1.114985
|
with self.__lock:
self.output.write(
to_str(data, self.encoding)
.encode()
.decode(self.out_encoding, errors="replace")
)
|
def _write_str(self, data)
|
Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()``
| 5.664919
| 5.800135
| 0.976688
|
if line is None:
# Empty line
self.write("\n")
else:
# Format the line, if arguments have been given
if args or kwargs:
line = line.format(*args, **kwargs)
with self.__lock:
# Write it
self.write(line)
try:
if line[-1] != "\n":
# Add the trailing new line
self.write("\n")
except IndexError:
# Got an empty string
self.write("\n")
self.flush()
|
def write_line(self, line=None, *args, **kwargs)
|
Formats and writes a line to the output
| 3.574214
| 3.46684
| 1.030972
|
if line is None:
# Empty line
line = ""
else:
# Format the line, if arguments have been given
if args or kwargs:
line = line.format(*args, **kwargs)
# Remove the trailing line feed
if line[-1] == "\n":
line = line[:-1]
# Write it
self.write(line)
self.flush()
|
def write_line_no_feed(self, line=None, *args, **kwargs)
|
Formats and writes a line to the output
| 3.427225
| 3.22365
| 1.063151
|
# Extract information from the context
logger_field = component_context.get_handler(constants.HANDLER_LOGGER)
if not logger_field:
# Error: log it and either raise an exception
# or ignore this handler
_logger.warning("Logger iPOPO handler can't find its configuration")
# Here, we ignore the error and do not give any handler to iPOPO
return []
else:
# Construct a handler and return it in a list
return [_LoggerHandler(logger_field, component_context.name)]
|
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
(never None)
| 10.772782
| 10.796039
| 0.997846
|
# Create the logger for this component instance
self._logger = logging.getLogger(self._name)
# Inject it
setattr(component_instance, self._field, self._logger)
|
def manipulate(self, stored_instance, component_instance)
|
Called by iPOPO right after the instantiation of the component.
This is the last chance to manipulate the component before the other
handlers start.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
| 7.688756
| 7.401538
| 1.038805
|
self._logger.debug("Component handlers are cleared")
# Clean up everything to avoid stale references, ...
self._field = None
self._name = None
self._logger = None
|
def clear(self)
|
Cleans up the handler. The handler can't be used after this method has
been called
| 16.086535
| 14.769722
| 1.089156
|
# type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]
if not current:
# No word yet, so the current position is after the existing ones
arg_idx = len(arguments)
else:
# Find the current word position
arg_idx = arguments.index(current)
# Find the ID of the next completer
completers = config.completers
if arg_idx > len(completers) - 1:
# Argument is too far to be positional, try
if config.multiple:
# Multiple calls allowed for the last completer
completer_id = completers[-1]
else:
# Nothing to return
return []
else:
completer_id = completers[arg_idx]
if completer_id == DUMMY:
# Dummy completer: do nothing
return []
# Find the matching service
svc_ref = context.get_service_reference(
SVC_COMPLETER, "({}={})".format(PROP_COMPLETER_ID, completer_id)
)
if svc_ref is None:
# Handler not found
_logger.debug("Unknown shell completer ID: %s", completer_id)
return []
# Call the completer
try:
with use_service(context, svc_ref) as completer:
matches = completer.complete(
config, prompt, session, context, arguments, current
)
if not matches:
return []
return matches
except Exception as ex:
_logger.exception("Error calling completer %s: %s", completer_id, ex)
return []
|
def completion_hints(config, prompt, session, context, current, arguments)
|
Returns the possible completions of the current argument
:param config: Configuration of the current completion
:param prompt: The shell prompt string
:param session: Current shell session
:param context: Context of the shell UI bundle
:param current: Current argument (to be completed)
:param arguments: List of all arguments in their current state
:return: A list of possible completions
| 3.39206
| 3.603381
| 0.941355
|
# Extract information from the context
logger_field = component_context.get_handler(constants.HANDLER_LOGGER)
if not logger_field:
# Error: log it and either raise an exception
# or ignore this handler
_logger.warning("Logger iPOPO handler can't find its configuration")
else:
# Create the logger for this component instance
logger = logging.getLogger(component_context.name)
# Inject it
setattr(instance, logger_field, logger)
logger.debug("Logger has been injected")
# No need to have an instance handler
return []
|
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
(never None)
| 8.326932
| 8.322026
| 1.000589
|
if not file_name:
return None
path = os.path.realpath(file_name)
if os.path.isfile(path):
return path
return None
|
def _resolve_file(file_name)
|
Checks if the file exists.
If the file exists, the method returns its absolute path.
Else, it returns None
:param file_name: The name of the file to check
:return: An absolute path, or None
| 2.840393
| 3.295687
| 0.861851
|
parser = argparse.ArgumentParser(add_help=False)
# Version number
parser.add_argument(
"--version",
action="version",
version="Pelix {0} from {1}".format(pelix.__version__, pelix.__file__),
)
# Framework options
group = parser.add_argument_group("Framework options")
group.add_argument(
"-D",
nargs="+",
dest="properties",
metavar="KEY=VALUE",
help="Sets framework properties",
)
group.add_argument(
"-v",
"--verbose",
action="store_true",
help="Set loggers to DEBUG level",
)
# Initial configuration
group = parser.add_argument_group("Initial configuration")
group.add_argument(
"-c",
"--conf",
dest="init_conf",
metavar="FILE",
help="Name of an initial configuration file to use "
"(default configuration is also loaded)",
)
group.add_argument(
"-C",
"--exclusive-conf",
dest="init_conf_exclusive",
metavar="FILE",
help="Name of an initial configuration file to use "
"(without the default configuration)",
)
group.add_argument(
"-e",
"--empty-conf",
dest="init_empty",
action="store_true",
help="Don't load any initial configuration",
)
# Initial script
group = parser.add_argument_group("Script execution arguments")
group.add_argument(
"--init",
action="store",
dest="init_script",
metavar="SCRIPT",
help="Runs the given shell script before starting the console",
)
group.add_argument(
"--run",
action="store",
dest="run_script",
metavar="SCRIPT",
help="Runs the given shell script then stops the framework",
)
return parser
|
def make_common_parser()
|
Creates an argument parser (argparse module) with the options that should
be common to all shells.
The result can be used as a parent parser (``parents`` argument in
``argparse.ArgumentParser``)
:return: An ArgumentParser object
| 2.318613
| 2.400895
| 0.965728
|
# Setup the logger
logging.basicConfig(
level=logging.DEBUG if parsed_args.verbose else logging.WARNING
)
# Framework properties dictionary
props = {}
# Read the initial configuration script
init = InitFileHandler()
if not parsed_args.init_empty:
if not parsed_args.init_conf_exclusive:
# Load default configuration
init.load()
# Load the given configuration file
conf_file = parsed_args.init_conf_exclusive or parsed_args.init_conf
if conf_file:
init.load(conf_file)
# Normalize configuration
init.normalize()
# Set initial framework properties
props.update(init.properties)
# Compute framework properties
for prop_def in parsed_args.properties or []:
key, value = prop_def.split("=", 1)
props[key] = value
# Check initial run script(s)
if parsed_args.init_script:
path = props[PROP_INIT_FILE] = _resolve_file(parsed_args.init_script)
if not path:
raise IOError(
"Initial script file not found: {0}".format(
parsed_args.init_script
)
)
if parsed_args.run_script:
# Find the file
path = props[PROP_RUN_FILE] = _resolve_file(parsed_args.run_script)
if not path:
raise IOError(
"Script file not found: {0}".format(parsed_args.run_script)
)
# Update the stored configuration
init.properties.update(props)
return init
|
def handle_common_arguments(parsed_args)
|
Handles the arguments defined by :meth:`~make_common_parser`
:param parsed_args: Argument parsed with ``argparse`` (``Namespace``)
:return: An :class:`~InitFileHandler` object
:raise IOError: Initial or run script not found
| 3.276034
| 3.044938
| 1.075895
|
# Parse arguments
parser = argparse.ArgumentParser(
prog="pelix.shell.console",
parents=[make_common_parser()],
description="Pelix Shell Console",
)
# Parse arguments
args = parser.parse_args(argv)
# Handle arguments
init = handle_common_arguments(args)
# Set the initial bundles
bundles = [
"pelix.ipopo.core",
"pelix.shell.core",
"pelix.shell.ipopo",
"pelix.shell.completion.pelix",
"pelix.shell.completion.ipopo",
"pelix.shell.console",
]
bundles.extend(init.bundles)
# Use the utility method to create, run and delete the framework
framework = pelix.create_framework(
remove_duplicates(bundles), init.properties
)
framework.start()
# Instantiate components
init.instantiate_components(framework.get_bundle_context())
try:
framework.wait_for_stop()
except KeyboardInterrupt:
framework.stop()
|
def main(argv=None)
|
Entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None
| 3.761345
| 3.834013
| 0.981046
|
sys.stdout.write(self.__get_ps1())
sys.stdout.flush()
return safe_input()
|
def _normal_prompt(self)
|
Flushes the prompt before requesting the input
:return: The command line
| 7.311009
| 10.352024
| 0.70624
|
# Start the init script
self._run_script(
self.__session, self._context.get_property(PROP_INIT_FILE)
)
# Run the script
script_file = self._context.get_property(PROP_RUN_FILE)
if script_file:
self._run_script(self.__session, script_file)
else:
# No script: run the main loop (blocking)
self._run_loop(self.__session)
# Nothing more to do
self._stop_event.set()
sys.stdout.write("Bye !\n")
sys.stdout.flush()
if on_quit is not None:
# Call a handler if needed
on_quit()
|
def loop_input(self, on_quit=None)
|
Reads the standard input until the shell session is stopped
:param on_quit: A call back method, called without argument when the
shell session has ended
| 4.228209
| 4.375198
| 0.966404
|
if file_path:
# The 'run' command returns False in case of error
# The 'execute' method returns False if the run command fails
return self._shell.execute('run "{0}"'.format(file_path), session)
return None
|
def _run_script(self, session, file_path)
|
Runs the given script file
:param session: Current shell session
:param file_path: Path to the file to execute
:return: True if a file has been execute
| 8.035368
| 8.281463
| 0.970284
|
try:
first_prompt = True
# Set up the prompt
prompt = (
self._readline_prompt
if readline is not None
else self._normal_prompt
)
while not self._stop_event.is_set():
# Wait for the shell to be there
# Before Python 2.7, wait() doesn't return a result
if self._shell_event.wait(.2) or self._shell_event.is_set():
# Shell present
if first_prompt:
# Show the banner on first prompt
sys.stdout.write(self._shell.get_banner())
first_prompt = False
# Read the next line
line = prompt()
with self._lock:
if self._shell_event.is_set():
# Execute it
self._shell.execute(line, session)
elif not self._stop_event.is_set():
# Shell service lost while not stopping
sys.stdout.write("Shell service lost.")
sys.stdout.flush()
except (EOFError, KeyboardInterrupt, SystemExit):
# Input closed or keyboard interruption
pass
|
def _run_loop(self, session)
|
Runs the main input loop
:param session: Current shell session
| 4.606766
| 4.609544
| 0.999397
|
if state == 0:
# New completion, reset the list of matches and the display hook
self._readline_matches = []
try:
readline.set_completion_display_matches_hook(None)
except AttributeError:
pass
# Get the full line
full_line = readline.get_line_buffer()
begin_idx = readline.get_begidx()
# Parse arguments as best as we can
try:
arguments = shlex.split(full_line)
except ValueError:
arguments = full_line.split()
# Extract the command (maybe with its namespace)
command = arguments.pop(0)
if begin_idx > 0:
# We're completing after the command (and maybe some args)
try:
# Find the command
ns, command = self._shell.get_ns_command(command)
except ValueError:
# Ambiguous command: ignore
return None
# Use the completer associated to the command, if any
try:
configuration = self._shell.get_command_completers(
ns, command
)
if configuration is not None:
self._readline_matches = completion_hints(
configuration,
self.__get_ps1(),
self.__session,
self._context,
text,
arguments,
)
except KeyError:
# Unknown command
pass
elif "." in command:
# Completing the command, and a name space is given
namespace, prefix = text.split(".", 2)
commands = self._shell.get_commands(namespace)
# Filter methods according to the prefix
self._readline_matches = [
"{0}.{1}".format(namespace, command)
for command in commands
if command.startswith(prefix)
]
else:
# Completing a command or namespace
prefix = command
# Default commands goes first...
possibilities = [
"{0} ".format(command)
for command in self._shell.get_commands(None)
if command.startswith(prefix)
]
# ... then name spaces
namespaces = self._shell.get_namespaces()
possibilities.extend(
"{0}.".format(namespace)
for namespace in namespaces
if namespace.startswith(prefix)
)
# ... then commands in those name spaces
possibilities.extend(
"{0} ".format(command)
for namespace in namespaces
if namespace is not None
for command in self._shell.get_commands(namespace)
if command.startswith(prefix)
)
# Filter methods according to the prefix
self._readline_matches = possibilities
if not self._readline_matches:
return None
# Return the first possibility
return self._readline_matches[0]
elif state < len(self._readline_matches):
# Next try
return self._readline_matches[state]
return None
|
def readline_completer(self, text, state)
|
A completer for the readline library
| 3.334804
| 3.307678
| 1.008201
|
with self._lock:
if self._shell is not None:
# A shell is already there
return
reference = self._context.get_service_reference(SERVICE_SHELL)
if reference is not None:
self.set_shell(reference)
|
def search_shell(self)
|
Looks for a shell service
| 5.063065
| 4.180335
| 1.211163
|
kind = event.get_kind()
reference = event.get_service_reference()
if kind in (pelix.ServiceEvent.REGISTERED, pelix.ServiceEvent.MODIFIED):
# A service matches our filter
self.set_shell(reference)
else:
with self._lock:
# Service is not matching our filter anymore
self.clear_shell()
# Request for a new binding
self.search_shell()
|
def service_changed(self, event)
|
Called by Pelix when an events changes
| 6.369383
| 5.532628
| 1.15124
|
if svc_ref is None:
return
with self._lock:
# Get the service
self._shell_ref = svc_ref
self._shell = self._context.get_service(self._shell_ref)
# Set the readline completer
if readline is not None:
readline.set_completer(self.readline_completer)
# Set the flag
self._shell_event.set()
|
def set_shell(self, svc_ref)
|
Binds the given shell service.
:param svc_ref: A service reference
| 3.753224
| 4.142968
| 0.905926
|
with self._lock:
# Clear the flag
self._shell_event.clear()
# Clear the readline completer
if readline is not None:
readline.set_completer(None)
del self._readline_matches[:]
if self._shell_ref is not None:
# Release the service
self._context.unget_service(self._shell_ref)
self._shell_ref = None
self._shell = None
|
def clear_shell(self)
|
Unbinds the active shell service
| 4.929169
| 4.389902
| 1.122843
|
# Exit the loop
with self._lock:
self._stop_event.set()
self._shell_event.clear()
if self._context is not None:
# Unregister from events
self._context.remove_service_listener(self)
# Release the shell
self.clear_shell()
self._context = None
|
def stop(self)
|
Clears all members
| 5.763147
| 5.945883
| 0.969267
|
# pylint: disable=C0103
try:
# Get the request content
data = to_str(request.read_data())
# Dispatch
result = self._marshaled_dispatch(data, self._simple_dispatch)
# Send the result
response.send_content(200, result, "application/json-rpc")
except Exception as ex:
response.send_content(
500, "Internal error:\n{0}\n".format(ex), "text/plain"
)
|
def do_POST(self, request, response)
|
Handles a HTTP POST request
:param request: The HTTP request bean
:param response: The HTTP response handler
| 4.100244
| 4.452324
| 0.920922
|
if not requires_filters or not isinstance(requires_filters, dict):
# No explicit filter configured
return requirements
# We need to change a part of the requirements
new_requirements = {}
for field, requirement in requirements.items():
try:
explicit_filter = requires_filters[field]
# Store an updated copy of the requirement
requirement_copy = requirement.copy()
requirement_copy.set_filter(explicit_filter)
new_requirements[field] = requirement_copy
except (KeyError, TypeError, ValueError):
# No information for this one, or invalid filter:
# keep the factory requirement
new_requirements[field] = requirement
return new_requirements
|
def _prepare_requirements(requirements, requires_filters)
|
Overrides the filters specified in the decorator with the given ones
:param requirements: Dictionary of requirements (field → Requirement)
:param requires_filters: Content of the 'requires.filter' component
property (field → string)
:return: The new requirements
| 4.491693
| 3.968785
| 1.131755
|
# Extract information from the context
requirements = component_context.get_handler(
ipopo_constants.HANDLER_REQUIRES
)
requires_filters = component_context.properties.get(
ipopo_constants.IPOPO_REQUIRES_FILTERS, None
)
# Prepare requirements
requirements = self._prepare_requirements(
requirements, requires_filters
)
# Set up the runtime dependency handlers
handlers = []
for field, requirement in requirements.items():
# Construct the handler
if requirement.aggregate:
handlers.append(AggregateDependency(field, requirement))
else:
handlers.append(SimpleDependency(field, requirement))
return 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
| 4.765525
| 5.084244
| 0.937313
|
# Store the stored instance...
self._ipopo_instance = stored_instance
# ... and the bundle context
self._context = stored_instance.bundle_context
|
def manipulate(self, stored_instance, component_instance)
|
Stores the given StoredInstance bean.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
| 11.09504
| 8.181306
| 1.356145
|
self._lock = None
self._ipopo_instance = None
self._context = None
self.requirement = None
self._value = None
self._field = None
|
def clear(self)
|
Cleans up the manager. The manager can't be used after this method has
been called
| 11.039505
| 10.993656
| 1.00417
|
if (
self._ipopo_instance is None
or not self._ipopo_instance.check_event(event)
):
# stop() and clean() may have been called after we have been put
# inside a listener list copy...
# or we've been told to ignore this event
return
# Call sub-methods
kind = event.get_kind()
svc_ref = event.get_service_reference()
if kind == ServiceEvent.REGISTERED:
# Service coming
self.on_service_arrival(svc_ref)
elif kind in (
ServiceEvent.UNREGISTERING,
ServiceEvent.MODIFIED_ENDMATCH,
):
# Service gone or not matching anymore
self.on_service_departure(svc_ref)
elif kind == ServiceEvent.MODIFIED:
# Modified properties (can be a new injection)
self.on_service_modify(svc_ref, event.get_previous_properties())
|
def service_changed(self, event)
|
Called by the framework when a service event occurs
| 5.179352
| 5.043248
| 1.026987
|
self._context.add_service_listener(
self, self.requirement.filter, self.requirement.specification
)
|
def start(self)
|
Starts the dependency manager
| 24.367905
| 21.189396
| 1.150005
|
self.reference = None
self._pending_ref = None
super(SimpleDependency, self).clear()
|
def clear(self)
|
Cleans up the manager. The manager can't be used after this method has
been called
| 14.664822
| 16.548037
| 0.886197
|
with self._lock:
if self._value is None:
# Inject the service
self.reference = svc_ref
self._value = self._context.get_service(svc_ref)
self._ipopo_instance.bind(self, self._value, self.reference)
return True
return None
|
def on_service_arrival(self, svc_ref)
|
Called when a service has been registered in the framework
:param svc_ref: A service reference
| 6.334745
| 7.65893
| 0.827106
|
with self._lock:
if self.reference is None:
# A previously registered service now matches our filter
self.on_service_arrival(svc_ref)
elif svc_ref is self.reference:
# Notify the property modification
self._ipopo_instance.update(
self, self._value, svc_ref, old_properties
)
|
def on_service_modify(self, svc_ref, old_properties)
|
Called when a service has been modified in the framework
:param svc_ref: A service reference
:param old_properties: Previous properties values
| 9.205134
| 11.033264
| 0.834307
|
super(SimpleDependency, self).stop()
if self.reference is not None:
# Return a tuple of tuple
return ((self._value, self.reference),)
return None
|
def stop(self)
|
Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None
| 12.2234
| 11.224298
| 1.089012
|
return super(SimpleDependency, self).is_valid() or (
self.requirement.immediate_rebind and self._pending_ref is not None
)
|
def is_valid(self)
|
Tests if the dependency is in a valid state
| 19.572908
| 15.114303
| 1.294992
|
with self._lock:
if self.reference is not None:
# Already bound
return
if self._pending_ref is not None:
# Get the reference we chose to keep this component valid
ref = self._pending_ref
self._pending_ref = None
else:
# Get the first matching service
ref = self._context.get_service_reference(
self.requirement.specification, self.requirement.filter
)
if ref is not None:
# Found a service
self.on_service_arrival(ref)
|
def try_binding(self)
|
Searches for the required service if needed
:raise BundleException: Invalid ServiceReference found
| 5.635182
| 4.974917
| 1.132719
|
self.services.clear()
self.services = None
self._future_value = None
super(AggregateDependency, self).clear()
|
def clear(self)
|
Cleans up the manager. The manager can't be used after this method has
been called
| 14.049703
| 14.777168
| 0.950771
|
with self._lock:
if svc_ref not in self.services:
# Get the new service
service = self._context.get_service(svc_ref)
if self._future_value is None:
# First value
self._future_value = []
# Store the information
self._future_value.append(service)
self.services[svc_ref] = service
self._ipopo_instance.bind(self, service, svc_ref)
return True
return None
|
def on_service_arrival(self, svc_ref)
|
Called when a service has been registered in the framework
:param svc_ref: A service reference
| 4.550678
| 5.112885
| 0.890041
|
with self._lock:
try:
# Get the service instance
service = self.services.pop(svc_ref)
except KeyError:
# Not a known service reference: ignore
pass
else:
# Clean the instance values
self._future_value.remove(service)
# Nullify the value if needed
if not self._future_value:
self._future_value = None
self._ipopo_instance.unbind(self, service, svc_ref)
return True
return None
|
def on_service_departure(self, svc_ref)
|
Called when a service has been unregistered from the framework
:param svc_ref: A service reference
:return: A tuple (service, reference) if the service has been lost,
else None
| 5.823357
| 5.320346
| 1.094545
|
with self._lock:
try:
# Look for the service
service = self.services[svc_ref]
except KeyError:
# A previously registered service now matches our filter
return self.on_service_arrival(svc_ref)
else:
# Notify the property modification
self._ipopo_instance.update(
self, service, svc_ref, old_properties
)
return None
|
def on_service_modify(self, svc_ref, old_properties)
|
Called when a service has been modified in the framework
:param svc_ref: A service reference
:param old_properties: Previous properties values
:return: A tuple (added, (service, reference)) if the dependency has
been changed, else None
| 7.412531
| 7.25212
| 1.022119
|
super(AggregateDependency, self).stop()
if self.services:
return [
(service, reference)
for reference, service in self.services.items()
]
return None
|
def stop(self)
|
Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None
| 10.053861
| 7.626681
| 1.318249
|
# Get the logger and log the message
self.__logs.append(entry)
# Notify listeners
for listener in self.__listeners.copy():
try:
listener.logged(entry)
except Exception as ex:
# Create a new log entry, without using logging nor notifying
# listener (to avoid a recursion)
err_entry = LogEntry(
logging.WARNING,
"Error notifying logging listener {0}: {1}".format(
listener, ex
),
sys.exc_info(),
self._context.get_bundle(),
None,
)
# Insert the new entry before the real one
self.__logs.pop()
self.__logs.append(err_entry)
self.__logs.append(entry)
|
def _store_entry(self, entry)
|
Stores a new log entry and notifies listeners
:param entry: A LogEntry object
| 4.992299
| 4.747936
| 1.051467
|
# pylint: disable=W0212
if not isinstance(reference, pelix.framework.ServiceReference):
# Ensure we have a clean Service Reference
reference = None
if exc_info is not None:
# Format the exception to avoid memory leaks
try:
exception_str = "\n".join(traceback.format_exception(*exc_info))
except (TypeError, ValueError, AttributeError):
exception_str = "<Invalid exc_info>"
else:
exception_str = None
# Store the LogEntry
entry = LogEntry(
level, message, exception_str, self.__bundle, reference
)
self.__reader._store_entry(entry)
|
def log(self, level, message, exc_info=None, reference=None)
|
Logs a message, possibly with an exception
:param level: Severity of the message (Python logging level)
:param message: Human readable message
:param exc_info: The exception context (sys.exc_info()), if any
:param reference: The ServiceReference associated to the log
| 3.879491
| 4.027661
| 0.963212
|
try:
# Get the module name
module_object = module_object.__name__
except AttributeError:
# We got a string
pass
return self._framework.get_bundle_by_name(module_object)
|
def _bundle_from_module(self, module_object)
|
Find the bundle associated to a module
:param module_object: A Python module object
:return: The Bundle object associated to the module, or None
| 5.09959
| 4.97433
| 1.025181
|
# pylint: disable=W0212
# Get the bundle
bundle = self._bundle_from_module(record.module)
# Convert to a LogEntry
entry = LogEntry(
record.levelno, record.getMessage(), None, bundle, None
)
self._reader._store_entry(entry)
|
def emit(self, record)
|
Handle a message logged with the logger
:param record: A log record
| 5.840797
| 6.579805
| 0.887685
|
# TODO: check (full transmission) success
return self._client.publish(topic, payload, qos, retain)
|
def publish(self, topic, payload, qos=0, retain=False)
|
Publishes an MQTT message
| 11.871498
| 16.325567
| 0.727172
|
if not requires_filters or not isinstance(requires_filters, dict):
# No explicit filter configured
return configs
# We need to change a part of the requirements
new_requirements = {}
for field, config in configs.items():
# Extract values from tuple
requirement, key, allow_none = config
try:
explicit_filter = requires_filters[field]
# Store an updated copy of the requirement
requirement_copy = requirement.copy()
requirement_copy.set_filter(explicit_filter)
new_requirements[field] = (requirement_copy, key, allow_none)
except (KeyError, TypeError, ValueError):
# No information for this one, or invalid filter:
# keep the factory requirement
new_requirements[field] = config
return new_requirements
|
def _prepare_requirements(configs, requires_filters)
|
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)
:return: The new configuration dictionary
| 5.196094
| 4.107142
| 1.265136
|
# Extract information from the context
configs = component_context.get_handler(
ipopo_constants.HANDLER_REQUIRES_MAP
)
requires_filters = component_context.properties.get(
ipopo_constants.IPOPO_REQUIRES_FILTERS, None
)
# Prepare requirements
configs = self._prepare_requirements(configs, requires_filters)
# Set up the runtime dependency handlers
handlers = []
for field, config in configs.items():
# Extract values from tuple
requirement, key, allow_none = config
# Construct the handler
if requirement.aggregate:
handlers.append(
AggregateDependency(field, requirement, key, allow_none)
)
else:
handlers.append(
SimpleDependency(field, requirement, key, allow_none)
)
return 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
| 5.18193
| 5.475157
| 0.946444
|
# Store the stored instance...
self._ipopo_instance = stored_instance
# ... and the bundle context
self._context = stored_instance.bundle_context
# Set the default value for the field: an empty dictionary
setattr(component_instance, self._field, {})
|
def manipulate(self, stored_instance, component_instance)
|
Stores the given StoredInstance bean.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
| 8.888971
| 7.73668
| 1.148939
|
self.services.clear()
self._future_value.clear()
self.services = None
self._lock = None
self._ipopo_instance = None
self._context = None
self.requirement = None
self._key = None
self._allow_none = None
self._future_value = None
self._field = None
|
def clear(self)
|
Cleans up the manager. The manager can't be used after this method has
been called
| 6.926977
| 6.698055
| 1.034177
|
return (
self.requirement is not None and self.requirement.optional
) or bool(self._future_value)
|
def is_valid(self)
|
Tests if the dependency is in a valid state
| 17.703888
| 15.943297
| 1.110428
|
self._context.remove_service_listener(self)
if self.services:
return [
(service, reference)
for reference, service in self.services.items()
]
return None
|
def stop(self)
|
Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None
| 6.972862
| 6.47649
| 1.076642
|
with self._lock:
if self.services:
# We already are alive (not our first call)
# => we are updated through service events
return
# Get all matching services
refs = self._context.get_all_service_references(
self.requirement.specification, self.requirement.filter
)
if not refs:
# No match found
return
results = []
try:
# Bind all new reference
for reference in refs:
added = self.on_service_arrival(reference)
if added:
results.append(reference)
except BundleException as ex:
# Get the logger for this instance
logger = logging.getLogger(
"-".join((self._ipopo_instance.name, "RequiresMap-Runtime"))
)
logger.debug("Error binding multiple references: %s", ex)
# Undo what has just been done, ignoring errors
for reference in results:
try:
self.on_service_departure(reference)
except BundleException as ex2:
logger.debug("Error cleaning up: %s", ex2)
del results[:]
raise
|
def try_binding(self)
|
Searches for the required service if needed
:raise BundleException: Invalid ServiceReference found
| 6.860288
| 6.204218
| 1.105746
|
with self._lock:
if svc_ref not in self.services:
# Get the key property
prop_value = svc_ref.get_property(self._key)
if (
prop_value not in self._future_value
and prop_value is not None
or self._allow_none
):
# Matching new property value
service = self._context.get_service(svc_ref)
# Store the information
self._future_value[prop_value] = service
self.services[svc_ref] = service
# Call back iPOPO
self._ipopo_instance.bind(self, service, svc_ref)
return True
return None
|
def on_service_arrival(self, svc_ref)
|
Called when a service has been registered in the framework
:param svc_ref: A service reference
| 5.04032
| 5.530551
| 0.911359
|
self._future_value.setdefault(key, []).append(service)
|
def __store_service(self, key, service)
|
Stores the given service in the dictionary
:param key: Dictionary key
:param service: Service to add to the dictionary
| 20.652573
| 23.992945
| 0.860777
|
try:
# Remove the injected service
prop_services = self._future_value[key]
prop_services.remove(service)
# Clean up
if not prop_services:
del self._future_value[key]
except KeyError:
# Ignore: can occur when removing a service with a None property,
# if allow_none is False
pass
|
def __remove_service(self, key, service)
|
Removes the given service from the future dictionary
:param key: Dictionary key
:param service: Service to remove from the dictionary
| 7.138587
| 7.297588
| 0.978212
|
with self._lock:
# The value field must be a deep copy of our dictionary
if self._future_value is not None:
return {
key: value[:] for key, value in self._future_value.items()
}
return None
|
def get_value(self)
|
Retrieves the value to inject in the component
:return: The value to inject
| 7.303048
| 7.77954
| 0.938751
|
with self._lock:
if svc_ref in self.services:
# Get the service instance
service = self.services.pop(svc_ref)
# Get the key property
prop_value = svc_ref.get_property(self._key)
# Remove the injected service
self.__remove_service(prop_value, service)
self._ipopo_instance.unbind(self, service, svc_ref)
return True
return None
|
def on_service_departure(self, svc_ref)
|
Called when a service has been unregistered from the framework
:param svc_ref: A service reference
:return: A tuple (service, reference) if the service has been lost,
else None
| 5.372447
| 4.83989
| 1.110035
|
with self._lock:
if svc_ref not in self.services:
# A previously registered service now matches our filter
return self.on_service_arrival(svc_ref)
else:
# Get the property values
service = self.services[svc_ref]
old_value = old_properties.get(self._key)
prop_value = svc_ref.get_property(self._key)
if old_value != prop_value:
# Key changed
if prop_value is not None or self._allow_none:
# New property accepted
if old_value is not None or self._allow_none:
self.__remove_service(old_value, service)
self.__store_service(prop_value, service)
# Notify the property modification, with a value change
self._ipopo_instance.update(
self, service, svc_ref, old_properties, True
)
else:
# Consider the service as gone
self.__remove_service(old_value, service)
del self.services[svc_ref]
self._ipopo_instance.unbind(self, service, svc_ref)
else:
# Simple property update
self._ipopo_instance.update(
self, service, svc_ref, old_properties, False
)
return None
|
def on_service_modify(self, svc_ref, old_properties)
|
Called when a service has been modified in the framework
:param svc_ref: A service reference
:param old_properties: Previous properties values
:return: A tuple (added, (service, reference)) if the dependency has
been changed, else None
| 3.582197
| 3.557912
| 1.006826
|
# type: (ServiceReference, Optional[Tuple[str, str]] ) -> bool
with self.__lock:
our_sr = self.get_reference()
if our_sr is None:
return False
sr_compare = our_sr == svc_ref
if cid is None:
return sr_compare
our_cid = self.get_export_container_id()
if our_cid is None:
return False
return sr_compare and our_cid == cid
|
def match_sr(self, svc_ref, cid=None)
|
Checks if this export registration matches the given service reference
:param svc_ref: A service reference
:param cid: A container ID
:return: True if the service matches this export registration
| 3.509216
| 3.769054
| 0.93106
|
# type: () -> Optional[Tuple[Any, Any, Any]]
with self.__lock:
return (
self.__updateexception
if self.__updateexception or self.__closed
else self.__exportref.get_exception()
)
|
def get_exception(self)
|
Returns the exception associated to the export
:return: An exception tuple, if any
| 9.003948
| 9.44818
| 0.952982
|
publish = False
exporterid = rsid = exception = export_ref = ed = None
with self.__lock:
if not self.__closed:
exporterid = self.__exportref.get_export_container_id()
export_ref = self.__exportref
rsid = self.__exportref.get_remoteservice_id()
ed = self.__exportref.get_description()
exception = self.__exportref.get_exception()
self.__closed = True
publish = self.__exportref.close(self)
self.__exportref = None
# pylint: disable=W0212
if publish and export_ref and self.__rsa:
self.__rsa._publish_event(
RemoteServiceAdminEvent.fromexportunreg(
self.__rsa._get_bundle(),
exporterid,
rsid,
export_ref,
exception,
ed,
)
)
self.__rsa = None
|
def close(self)
|
Cleans up the export endpoint
| 5.469794
| 5.121827
| 1.067938
|
endpoint_id = endpoint_description.get_id()
with self._published_endpoints_lock:
if self.get_advertised_endpoint(endpoint_id) is not None:
return False
advertise_result = self._advertise(endpoint_description)
if advertise_result:
self._add_advertised(endpoint_description, advertise_result)
return True
return False
|
def advertise_endpoint(self, endpoint_description)
|
Advertise and endpoint_description for remote discovery.
If it hasn't already been a endpoint_description will be advertised via
a some protocol.
:param endpoint_description: an instance of EndpointDescription to
advertise. Must not be None.
:return: True if advertised, False if not
(e.g. it's already been advertised)
| 3.042752
| 3.083416
| 0.986812
|
endpoint_id = updated_ed.get_id()
with self._published_endpoints_lock:
if self.get_advertised_endpoint(endpoint_id) is None:
return False
advertise_result = self._update(updated_ed)
if advertise_result:
self._remove_advertised(endpoint_id)
self._add_advertised(updated_ed, advertise_result)
return True
return False
|
def update_endpoint(self, updated_ed)
|
Update a previously advertised endpoint_description.
:param endpoint_description: an instance of EndpointDescription to
update. Must not be None.
:return: True if advertised, False if not
(e.g. it's already been advertised)
| 3.489114
| 3.181283
| 1.096763
|
with self._published_endpoints_lock:
with self._published_endpoints_lock:
advertised = self.get_advertised_endpoint(endpointid)
if not advertised:
return None
unadvertise_result = self._unadvertise(advertised)
if unadvertise_result:
self._remove_advertised(endpointid)
return None
|
def unadvertise_endpoint(self, endpointid)
|
Unadvertise a previously-advertised endpointid (string).
:param endpointid. The string returned from ed.get_id() or
the value of property endpoint.id. Should not be None
:return True if removed, False if not removed (hasn't been previously advertised
by this advertiser
| 3.380035
| 3.878921
| 0.871386
|
# Retrieve the handler configuration
provides = component_context.get_handler(
ipopo_constants.HANDLER_PROVIDES
)
if not provides:
# Nothing to do
return ()
# 1 handler per provided service
return [
ServiceRegistrationHandler(
specs, controller, is_factory, is_prototype
)
for specs, controller, is_factory, is_prototype in provides
]
|
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
| 8.957621
| 9.038808
| 0.991018
|
# Local variable, to avoid messing with "self"
stored_instance = self._ipopo_instance
def get_value(self, name):
# pylint: disable=W0613
return stored_instance.get_controller_state(name)
def set_value(self, name, new_value):
# pylint: disable=W0613
# Get the previous value
old_value = stored_instance.get_controller_state(name)
if new_value != old_value:
# Update the controller state
stored_instance.set_controller_state(name, new_value)
return new_value
return get_value, set_value
|
def _field_controller_generator(self)
|
Generates the methods called by the injected controller
| 3.231894
| 3.159901
| 1.022783
|
# Store the stored instance
self._ipopo_instance = stored_instance
if self.__controller is None:
# No controller: do nothing
return
# Get the current value of the member (True by default)
controller_value = getattr(component_instance, self.__controller, True)
# Store the controller value
stored_instance.set_controller_state(
self.__controller, controller_value
)
# Prepare the methods names
getter_name = "{0}{1}".format(
ipopo_constants.IPOPO_CONTROLLER_PREFIX,
ipopo_constants.IPOPO_GETTER_SUFFIX,
)
setter_name = "{0}{1}".format(
ipopo_constants.IPOPO_CONTROLLER_PREFIX,
ipopo_constants.IPOPO_SETTER_SUFFIX,
)
# Inject the getter and setter at the instance level
getter, setter = self._field_controller_generator()
setattr(component_instance, getter_name, getter)
setattr(component_instance, setter_name, setter)
|
def manipulate(self, stored_instance, component_instance)
|
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
| 3.464039
| 3.325491
| 1.041662
|
if self.__controller != name:
# Nothing to do
return
# Update the controller value
self.__controller_on = value
if value:
# Controller switched to "ON"
self._register_service()
else:
# Controller switched to "OFF"
self._unregister_service()
|
def on_controller_change(self, name, value)
|
Called by the instance manager when a controller value has been
modified
:param name: The name of the controller
:param value: The new value of the controller
| 5.018259
| 6.279949
| 0.799092
|
if self._registration is not None:
# use the registration to trigger the service event
self._registration.set_properties({name: new_value})
|
def on_property_change(self, name, old_value, new_value)
|
Called by the instance manager when a component property is modified
:param name: The changed property name
:param old_value: The previous property value
:param new_value: The new property value
| 7.678299
| 9.743699
| 0.788027
|
if (
self._registration is None
and self.specifications
and self.__validated
and self.__controller_on
):
# Use a copy of component properties
properties = self._ipopo_instance.context.properties.copy()
bundle_context = self._ipopo_instance.bundle_context
# Register the service
self._registration = bundle_context.register_service(
self.specifications,
self._ipopo_instance.instance,
properties,
factory=self.__is_factory,
prototype=self.__is_prototype,
)
self._svc_reference = self._registration.get_reference()
# Notify the component
self._ipopo_instance.safe_callback(
ipopo_constants.IPOPO_CALLBACK_POST_REGISTRATION,
self._svc_reference,
)
|
def _register_service(self)
|
Registers the provided service, if possible
| 5.180144
| 4.963804
| 1.043584
|
if self._registration is not None:
# Ignore error
try:
self._registration.unregister()
except BundleException as ex:
# Only log the error at this level
logger = logging.getLogger(
"-".join((self._ipopo_instance.name, "ServiceRegistration"))
)
logger.error("Error unregistering a service: %s", ex)
# Notify the component (even in case of error)
self._ipopo_instance.safe_callback(
ipopo_constants.IPOPO_CALLBACK_POST_UNREGISTRATION,
self._svc_reference,
)
self._registration = None
self._svc_reference = None
|
def _unregister_service(self)
|
Unregisters the provided service, if needed
| 5.161572
| 4.955027
| 1.041684
|
if svc_reference is None:
raise TypeError("Invalid ServiceReference")
try:
# Give the service
yield bundle_context.get_service(svc_reference)
finally:
try:
# Release it
bundle_context.unget_service(svc_reference)
except pelix.constants.BundleException:
# Service might have already been unregistered
pass
|
def use_service(bundle_context, svc_reference)
|
Utility context to safely use a service in a "with" block.
It looks after the the given service and releases its reference when
exiting the context.
:param bundle_context: The calling bundle context
:param svc_reference: The reference of the service to use
:return: The requested service
:raise BundleException: Service not found
:raise TypeError: Invalid service reference
| 3.427308
| 3.923028
| 0.873638
|
# pylint: disable=C1801
# Filter the names (remove empty ones)
locks_attr_names = [
lock_name for lock_name in locks_attr_names if lock_name
]
if not locks_attr_names:
raise ValueError("The lock names list can't be empty")
if "sorted" not in kwargs or kwargs["sorted"]:
# Sort the lock names if requested
# (locking always in the same order reduces the risk of dead lock)
locks_attr_names = list(locks_attr_names)
locks_attr_names.sort()
def wrapped(method):
@functools.wraps(method)
def synchronized(self, *args, **kwargs):
# Raises an AttributeError if needed
locks = [getattr(self, attr_name) for attr_name in locks_attr_names]
locked = collections.deque()
i = 0
try:
# Lock
for lock in locks:
if lock is None:
# No lock...
raise AttributeError(
"Lock '{0}' can't be None in class {1}".format(
locks_attr_names[i], type(self).__name__
)
)
# Get the lock
i += 1
lock.acquire()
locked.appendleft(lock)
# Use the method
return method(self, *args, **kwargs)
finally:
# Unlock what has been locked in all cases
for lock in locked:
lock.release()
locked.clear()
del locks[:]
return synchronized
# Return the wrapped method
return wrapped
|
def SynchronizedClassMethod(*locks_attr_names, **kwargs)
|
A synchronizer decorator for class methods. An AttributeError can be raised
at runtime if the given lock attribute doesn't exist or if it is None.
If a parameter ``sorted`` is found in ``kwargs`` and its value is True,
then the list of locks names will be sorted before locking.
:param locks_attr_names: A list of the lock(s) attribute(s) name(s) to be
used for synchronization
:return: The decorator method, surrounded with the lock
| 3.301362
| 3.262717
| 1.011844
|
if lock is None:
# Don't do useless tests
return False
for attr in "acquire", "release", "__enter__", "__exit__":
if not hasattr(lock, attr):
# Missing something
return False
# Same API as a lock
return True
|
def is_lock(lock)
|
Tests if the given lock is an instance of a lock class
| 7.339797
| 7.227567
| 1.015528
|
if items is None:
return items
new_list = []
for item in items:
if item not in new_list:
new_list.append(item)
return new_list
|
def remove_duplicates(items)
|
Returns a list without duplicates, keeping elements order
:param items: A list of items
:return: The list without duplicates, in the same order
| 2.135204
| 2.328864
| 0.916844
|
if listener is None or listener in registry:
return False
registry.append(listener)
return True
|
def add_listener(registry, listener)
|
Adds a listener in the registry, if it is not yet in
:param registry: A registry (a list)
:param listener: The listener to register
:return: True if the listener has been added
| 4.630804
| 5.97716
| 0.77475
|
if listener is not None and listener in registry:
registry.remove(listener)
return True
return False
|
def remove_listener(registry, listener)
|
Removes a listener from the registry
:param registry: A registry (a list)
:param listener: The listener to remove
:return: True if the listener was in the list
| 3.907562
| 5.746304
| 0.680013
|
if value is None:
# None given
if allow_none:
return None
return []
elif isinstance(value, (list, tuple, set, frozenset)):
# Iterable given, return it as-is
return value
# Return a one-value list
return [value]
|
def to_iterable(value, allow_none=True)
|
Tries to convert the given value to an iterable, if necessary.
If the given value is a list, a list is returned; if it is a string, a list
containing one string is returned, ...
:param value: Any object
:param allow_none: If True, the method returns None if value is None, else
it returns an empty list
:return: A list containing the given string, or the given value
| 3.886333
| 5.027776
| 0.772973
|
if not self.__already_logged:
# Print only if not already done
stack = "\n\t".join(traceback.format_stack())
logging.getLogger(self.__logger).warning(
"%s: %s\n%s", method_name, self.__message, stack
)
self.__already_logged = True
|
def __log(self, method_name)
|
Logs the deprecation message on first call, does nothing after
:param method_name: Name of the deprecated method
| 4.467266
| 4.981277
| 0.896811
|
# type: () -> bool
with self.__lock:
self.__value -= 1
if self.__value == 0:
# All done
self.__event.set()
return True
elif self.__value < 0:
# Gone too far
raise ValueError("The counter has gone below 0")
return False
|
def step(self)
|
Decreases the internal counter. Raises an error if the counter goes
below 0
:return: True if this step was the final one, else False
:raise ValueError: The counter has gone below 0
| 5.0242
| 4.552052
| 1.103722
|
# type: (str, ShellSession, BundleContext, List[str], int) -> None
# Prepare a line pattern for each match
match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len)
# Sort matching IDs
matches = sorted(int(match) for match in matches)
# Print the match and the associated name
session.write_line()
for bnd_id in matches:
bnd = context.get_bundle(bnd_id)
session.write_line(match_pattern, bnd_id, bnd.get_symbolic_name())
# Print the prompt, then current line
session.write(prompt)
session.write_line_no_feed(readline.get_line_buffer())
readline.redisplay()
|
def display_hook(prompt, session, context, matches, longest_match_len)
|
Displays the available bundle matches and the bundle name
:param prompt: Shell prompt string
:param session: Current shell session (for display)
:param context: BundleContext of the shell
:param matches: List of words matching the substitution
:param longest_match_len: Length of the largest match
| 4.688455
| 5.138512
| 0.912415
|
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
# Register a method to display helpful completion
self.set_display_hook(self.display_hook, prompt, session, context)
# Return a list of bundle IDs (strings) matching the current value
# and not yet in arguments
rl_matches = []
for bnd in context.get_bundles():
bnd_id = "{0} ".format(bnd.get_bundle_id())
if bnd_id.startswith(current):
rl_matches.append(bnd_id)
return rl_matches
|
def complete(
self, config, prompt, session, context, current_arguments, current
)
|
Returns the list of bundle IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_arguments: Current arguments (without the command itself)
:param current: Current word
:return: A list of matches
| 5.917331
| 6.01532
| 0.98371
|
# type: (str, ShellSession, BundleContext, List[str], int) -> None
try:
# Prepare a line pattern for each match
match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len)
# Sort matching IDs
matches = sorted(int(match) for match in matches)
# Print the match and the associated name
session.write_line()
for svc_id in matches:
svc_ref = context.get_service_reference(
None, "({}={})".format(SERVICE_ID, svc_id)
)
session.write_line(match_pattern, svc_id, str(svc_ref))
# Print the prompt, then current line
session.write(prompt)
session.write_line_no_feed(readline.get_line_buffer())
readline.redisplay()
except Exception as ex:
session.write_line("\n{}\n\n", ex)
|
def display_hook(prompt, session, context, matches, longest_match_len)
|
Displays the available services matches and the service details
:param prompt: Shell prompt string
:param session: Current shell session (for display)
:param context: BundleContext of the shell
:param matches: List of words matching the substitution
:param longest_match_len: Length of the largest match
| 4.681937
| 4.857542
| 0.963849
|
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
# Register a method to display helpful completion
self.set_display_hook(self.display_hook, prompt, session, context)
# Return a list of bundle IDs (strings) matching the current value
# and not yet in arguments
rl_matches = []
for svc_ref in context.get_all_service_references(None, None):
svc_id = "{0} ".format(svc_ref.get_property(SERVICE_ID))
if svc_id.startswith(current):
rl_matches.append(svc_id)
return rl_matches
|
def complete(
self, config, prompt, session, context, current_arguments, current
)
|
Returns the list of services IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_arguments: Current arguments (without the command itself)
:param current: Current word
:return: A list of matches
| 5.757986
| 5.996981
| 0.960147
|
return self._get_or_create_container(
exported_configs, service_intents, export_props
)
|
def supports_export(self, exported_configs, service_intents, export_props)
|
Method called by rsa.export_service to ask if this
ExportDistributionProvider supports export for given
exported_configs (list), service_intents (list), and
export_props (dict).
If a ExportContainer instance is returned then it is used to export
the service. If None is returned, then this distribution provider will
not be used to export the service.
The default implementation returns self._get_or_create_container.
| 5.504657
| 2.631171
| 2.092094
|
return self._get_or_create_container(
exported_configs, service_intents, endpoint_props
)
|
def supports_import(
self, exported_configs, service_intents, endpoint_props
)
|
Method called by rsa.export_service to ask if this
ImportDistributionProvider supports import for given
exported_configs (list), service_intents (list), and
export_props (dict).
If a ImportContainer instance is returned then it is used to import
the service. If None is returned, then this distribution provider will
not be used to import the service.
The default implementation returns self._get_or_create_container.
| 5.874161
| 2.295377
| 2.559127
|
# type: () -> bool
assert self._bundle_context
assert self._container_props is not None
assert self._get_distribution_provider()
assert self.get_config_name()
assert self.get_namespace()
return True
|
def is_valid(self)
|
Checks if the component is valid
:return: Always True if it doesn't raise an exception
:raises AssertionError: Invalid properties
| 8.599449
| 11.27264
| 0.76286
|
# type: (BundleContext, Dict[str, Any]) -> None
self._bundle_context = bundle_context
self._container_props = container_props
self.is_valid()
|
def _validate_component(self, bundle_context, container_props)
|
Component validated
:param bundle_context: Bundle context
:param container_props: Instance properties
:raises AssertionError: Invalid properties
| 3.415376
| 4.213621
| 0.810556
|
# type: (str, Tuple[Any, EndpointDescription]) -> None
with self._exported_instances_lock:
self._exported_services[ed_id] = inst
|
def _add_export(self, ed_id, inst)
|
Keeps track of an exported service
:param ed_id: ID of the endpoint description
:param inst: A tuple: (service instance, endpoint description)
| 7.045197
| 6.086895
| 1.157437
|
# type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]]
with self._exported_instances_lock:
for val in self._exported_services.values():
if func(val):
return val
return None
|
def _find_export(self, func)
|
Look for an export using the given lookup method
The lookup method must accept a single parameter, which is a tuple
containing a service instance and endpoint description.
:param func: A function to look for the excepted export
:return: The found tuple or None
| 5.661911
| 6.023246
| 0.94001
|
# type: (Any, EndpointDescription) -> None
self._add_export(ed.get_id(), (svc, ed))
|
def _export_service(self, svc, ed)
|
Registers a service export
:param svc: Service instance
:param ed: Endpoint description
| 9.013359
| 10.600035
| 0.850314
|
# type: (List[str], ServiceReference, Dict[str, Any]) -> Dict[str, Any]
pkg_vers = rsa.get_package_versions(intfs, export_props)
exported_configs = get_string_plus_property_value(
svc_ref.get_property(SERVICE_EXPORTED_CONFIGS)
)
if not exported_configs:
exported_configs = [self.get_config_name()]
service_intents = set()
svc_intents = export_props.get(SERVICE_INTENTS, None)
if svc_intents:
service_intents.update(svc_intents)
svc_exp_intents = export_props.get(SERVICE_EXPORTED_INTENTS, None)
if svc_exp_intents:
service_intents.update(svc_exp_intents)
svc_exp_intents_extra = export_props.get(
SERVICE_EXPORTED_INTENTS_EXTRA, None
)
if svc_exp_intents_extra:
service_intents.update(svc_exp_intents_extra)
rsa_props = rsa.get_rsa_props(
intfs,
exported_configs,
self._get_supported_intents(),
svc_ref.get_property(SERVICE_ID),
export_props.get(ENDPOINT_FRAMEWORK_UUID),
pkg_vers,
list(service_intents),
)
ecf_props = rsa.get_ecf_props(
self.get_id(),
self.get_namespace(),
rsa.get_next_rsid(),
rsa.get_current_time_millis(),
)
extra_props = rsa.get_extra_props(export_props)
merged = rsa.merge_dicts(rsa_props, ecf_props, extra_props)
# remove service.bundleid
merged.pop(SERVICE_BUNDLE_ID, None)
# remove service.scope
merged.pop(SERVICE_SCOPE, None)
return merged
|
def prepare_endpoint_props(self, intfs, svc_ref, export_props)
|
Sets up the properties of an endpoint
:param intfs: Specifications to export
:param svc_ref: Reference of the exported service
:param export_props: Export properties
:return: The properties of the endpoint
| 2.729606
| 2.995277
| 0.911304
|
# type: (ServiceReference, Dict[str, Any]) -> EndpointDescription
ed = EndpointDescription.fromprops(export_props)
self._export_service(
self._get_bundle_context().get_service(svc_ref), ed
)
return ed
|
def export_service(self, svc_ref, export_props)
|
Exports the given service
:param svc_ref: Reference to the service to export
:param export_props: Export properties
:return: The endpoint description
| 4.881235
| 7.138043
| 0.683834
|
# Prepare arguments
parser = argparse.ArgumentParser(
prog="pelix.shell.xmpp",
parents=[make_common_parser()],
description="Pelix XMPP Shell",
)
group = parser.add_argument_group("XMPP options")
group.add_argument("-j", "--jid", dest="jid", help="Jabber ID")
group.add_argument("--password", dest="password", help="JID password")
group.add_argument("-s", "--server", dest="server", help="XMPP server host")
group.add_argument(
"-p",
"--port",
dest="port",
type=int,
default=5222,
help="XMPP server port",
)
group.add_argument(
"--tls",
dest="use_tls",
action="store_true",
help="Use a STARTTLS connection",
)
group.add_argument(
"--ssl",
dest="use_ssl",
action="store_true",
help="Use an SSL connection",
)
# Parse them
args = parser.parse_args(argv)
# Handle common arguments
init = handle_common_arguments(args)
# Quiet down the SleekXMPP logger
if not args.verbose:
logging.getLogger("sleekxmpp").setLevel(logging.WARNING)
if not args.server and not args.jid:
_logger.error("No JID nor server given. Abandon.")
sys.exit(1)
# Get the password if necessary
password = args.password
if args.jid and args.password is None:
try:
import getpass
except ImportError:
_logger.error(
"getpass() unavailable: give a password in command line"
)
else:
try:
password = getpass.getpass()
except getpass.GetPassWarning:
pass
# Get the server from the JID, if necessary
server = args.server
if not server:
server = sleekxmpp.JID(args.jid).domain
# Set the initial bundles
bundles = [
"pelix.ipopo.core",
"pelix.shell.core",
"pelix.shell.ipopo",
"pelix.shell.console",
"pelix.shell.xmpp",
]
bundles.extend(init.bundles)
# Use the utility method to create, run and delete the framework
framework = pelix.framework.create_framework(
remove_duplicates(bundles), init.properties
)
framework.start()
# Instantiate a Remote Shell
with use_ipopo(framework.get_bundle_context()) as ipopo:
ipopo.instantiate(
pelix.shell.FACTORY_XMPP_SHELL,
"xmpp-shell",
{
"shell.xmpp.server": server,
"shell.xmpp.port": args.port,
"shell.xmpp.jid": args.jid,
"shell.xmpp.password": password,
"shell.xmpp.tls": args.use_tls,
"shell.xmpp.ssl": args.use_ssl,
},
)
# Instantiate configured components
init.instantiate_components(framework.get_bundle_context())
try:
framework.wait_for_stop()
except KeyboardInterrupt:
framework.stop()
|
def main(argv=None)
|
Entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None
| 2.468724
| 2.486563
| 0.992826
|
# Flush buffer
content = self._buffer.getvalue()
self._buffer = StringIO()
if content:
# Send message
self._client.send_message(self._target, content, mtype="chat")
|
def flush(self)
|
Sends buffered data to the target
| 5.58314
| 5.79153
| 0.964018
|
# type: (Any, ServiceRegistration) -> Any
svc_ref = svc_registration.get_reference()
try:
# Use the existing service
service, counter = self.__factored[svc_ref]
counter.inc()
except KeyError:
# Create the service
service = factory.get_service(self.__bundle, svc_registration)
counter = _UsageCounter()
counter.inc()
# Store the counter
self.__factored[svc_ref] = (service, counter)
return service
|
def _get_from_factory(self, factory, svc_registration)
|
Returns a service instance from a Prototype Service Factory
:param factory: The prototype service factory
:param svc_registration: The ServiceRegistration object
:return: The requested service instance returned by the factory
| 4.030685
| 5.07743
| 0.793844
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.