code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# type: (int, str, str, str, int) -> None self.set_response(http_code, http_message) if mime_type and not self.is_header_set("content-type"): self.set_header("content-type", mime_type) # Convert the content raw_content = to_bytes(content) if content_length is not None and not self.is_header_set( "content-length" ): if content_length < 0: # Compute the length content_length = len(raw_content) # Send the length self.set_header("content-length", content_length) self.end_headers() # Send the content self.write(raw_content)
def send_content( self, http_code, content, mime_type="text/html", http_message=None, content_length=-1, )
Utility method to send the given content as an answer. You can still use get_wfile or write afterwards, if you forced the content length. If content_length is negative (default), it will be computed as the length of the content; if it is positive, the given value will be used; if it is None, the content-length header won't be sent. :param http_code: HTTP result code :param content: Data to be sent (must be a string) :param mime_type: Content MIME type (content-type) :param http_message: HTTP code description :param content_length: Forced content length
2.456374
2.798925
0.877614
if not address: raise ValueError("Empty address") # Convert the address to a binary form group_bin = pton(family, address) if family == socket.AF_INET: # IPv4 # struct ip_mreq # { # struct in_addr imr_multiaddr; /* IP multicast address of group */ # struct in_addr imr_interface; /* local IP address of interface */ # }; # "=I" : Native order, standard size unsigned int return group_bin + struct.pack("=I", socket.INADDR_ANY) elif family == socket.AF_INET6: # IPv6 # struct ipv6_mreq { # struct in6_addr ipv6mr_multiaddr; # unsigned int ipv6mr_interface; # }; # "@I" : Native order, native size unsigned int return group_bin + struct.pack("@I", 0) raise ValueError("Unknown family {0}".format(family))
def make_mreq(family, address)
Makes a mreq structure object for the given address and socket family. :param family: A socket family (AF_INET or AF_INET6) :param address: A multicast address (group) :raise ValueError: Invalid family or address
3.957461
4.085239
0.968722
# Get the information about a datagram (UDP) socket, of any family try: addrs_info = socket.getaddrinfo( address, port, socket.AF_UNSPEC, socket.SOCK_DGRAM ) except socket.gaierror: raise ValueError( "Error retrieving address informations ({0}, {1})".format( address, port ) ) if len(addrs_info) > 1: _logger.debug( "More than one address information found. Using the first one." ) # Get the first entry : (family, socktype, proto, canonname, sockaddr) addr_info = addrs_info[0] # Only accept IPv4/v6 addresses if addr_info[0] not in (socket.AF_INET, socket.AF_INET6): # Unhandled address family raise ValueError("Unhandled socket family : %d" % (addr_info[0])) # Prepare the socket sock = socket.socket(addr_info[0], socket.SOCK_DGRAM, socket.IPPROTO_UDP) # Reuse address sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, "SO_REUSEPORT"): # Special for MacOS # pylint: disable=E1101 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # Bind the socket if sock.family == socket.AF_INET: # IPv4 binding sock.bind(("0.0.0.0", port)) else: # IPv6 Binding sock.bind(("::", port)) # Prepare the mreq structure to join the group # addrinfo[4] = (addr,port) mreq = make_mreq(sock.family, addr_info[4][0]) # Join the group if sock.family == socket.AF_INET: # IPv4 sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) # Allow multicast packets to get back on this host sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) elif sock.family == socket.AF_INET6: # IPv6 sock.setsockopt(ipproto_ipv6(), socket.IPV6_JOIN_GROUP, mreq) # Allow multicast packets to get back on this host sock.setsockopt(ipproto_ipv6(), socket.IPV6_MULTICAST_LOOP, 1) return sock, addr_info[4][0]
def create_multicast_socket(address, port)
Creates a multicast socket according to the given address and port. Handles both IPv4 and IPv6 addresses. :param address: Multicast address/group :param port: Socket port :return: A tuple (socket, listening address) :raise ValueError: Invalid address or port
2.325845
2.3256
1.000105
if sock is None: return if address: # Prepare the mreq structure to join the group mreq = make_mreq(sock.family, address) # Quit group if sock.family == socket.AF_INET: # IPv4 sock.setsockopt(socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, mreq) elif sock.family == socket.AF_INET6: # IPv6 sock.setsockopt(ipproto_ipv6(), socket.IPV6_LEAVE_GROUP, mreq) # Close the socket sock.close()
def close_multicast_socket(sock, address)
Cleans up the given multicast socket. Unregisters it of the multicast group. Parameters should be the result of create_multicast_socket :param sock: A multicast socket :param address: The multicast address used by the socket
3.0031
3.36866
0.891482
print( "Python.sayHello called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonSync says: Howdy {0} " "that's a nice runtime you got there".format(name) )
def sayHello(self, name="Not given", message="nothing")
Synchronous implementation of IHello.sayHello synchronous method. The remote calling thread will be blocked until this is executed and responds.
10.437175
10.414569
1.002171
print( "Python.sayHelloAsync called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonAsync says: Howdy {0} " "that's a nice runtime you got there".format(name) )
def sayHelloAsync(self, name="Not given", message="nothing")
Implementation of IHello.sayHelloAsync. This method will be executed via some thread, and the remote caller will not block. This method should return either a String result (since the return type of IHello.sayHelloAsync is CompletableFuture<String>, OR a Future that returns a python string. In this case, it returns the string directly.
8.958086
9.352591
0.957819
print( "Python.sayHelloPromise called by: {0} " "with message: '{1}'".format(name, message) ) return ( "PythonPromise says: Howdy {0} " "that's a nice runtime you got there".format(name) )
def sayHelloPromise(self, name="Not given", message="nothing")
Implementation of IHello.sayHelloPromise. This method will be executed via some thread, and the remote caller will not block.
9.302206
9.551882
0.973861
# type: (type, Optional[BundleContext]) -> Optional[FactoryContext] try: # Try to get the factory context (built using decorators) context = getattr(factory_class, constants.IPOPO_FACTORY_CONTEXT) except AttributeError: # The class has not been manipulated, or too badly return None if not context.completed: # Partial context (class not manipulated) return None # Associate the factory to the bundle context context.set_bundle_context(bundle_context) return context
def _set_factory_context(factory_class, bundle_context)
Transforms the context data dictionary into its FactoryContext object form. :param factory_class: A manipulated class :param bundle_context: The class bundle context :return: The factory context, None on error
6.557156
6.854574
0.95661
# type: (Bundle) -> List[Tuple[FactoryContext, type]] result = [] # Get the Python module module_ = bundle.get_module() # Get the bundle context bundle_context = bundle.get_bundle_context() for name in dir(module_): try: # Get the module member factory_class = getattr(module_, name) if not inspect.isclass(factory_class): continue # Check if it is a class if sys.modules[factory_class.__module__] is not module_: # Only keep classes from this module continue except (AttributeError, KeyError): # getattr() didn't work or __module__ is not a member of the class, # or the module is not known by the interpreter continue context = _set_factory_context(factory_class, bundle_context) if context is None: # Error setting up the factory context continue result.append((context, factory_class)) return result
def _load_bundle_factories(bundle)
Retrieves a list of pairs (FactoryContext, factory class) with all readable manipulated classes found in the bundle. :param bundle: A Bundle object :return: The list of factories loaded from the bundle
3.583949
3.705598
0.967171
# Get the references svc_refs = self.__context.get_all_service_references( handlers_const.SERVICE_IPOPO_HANDLER_FACTORY ) if svc_refs: for svc_ref in svc_refs: # Store each handler factory self.__add_handler_factory(svc_ref)
def __find_handler_factories(self)
Finds all registered handler factories and stores them
5.689708
5.425992
1.048602
# type: (ServiceReference) -> None with self.__handlers_lock: # Get the handler ID handler_id = svc_ref.get_property(handlers_const.PROP_HANDLER_ID) if handler_id in self._handlers: # Duplicated ID _logger.warning("Already registered handler ID: %s", handler_id) else: # Store the service self._handlers_refs.add(svc_ref) self._handlers[handler_id] = self.__context.get_service(svc_ref) # Try to instantiate waiting components succeeded = set() for ( name, (context, instance), ) in self.__waiting_handlers.items(): if self.__try_instantiate(context, instance): succeeded.add(name) # Remove instantiated component from the waiting list for name in succeeded: del self.__waiting_handlers[name]
def __add_handler_factory(self, svc_ref)
Stores a new handler factory :param svc_ref: ServiceReference of the new handler factory
3.738937
3.998442
0.935098
# type: (ServiceReference) -> None with self.__handlers_lock: # Get the handler ID handler_id = svc_ref.get_property(handlers_const.PROP_HANDLER_ID) # Check if this is the handler we use if svc_ref not in self._handlers_refs: return # Clean up self.__context.unget_service(svc_ref) self._handlers_refs.remove(svc_ref) del self._handlers[handler_id] # List the components using this handler to_stop = set() # type: Set[StoredInstance] for factory_name in self.__factories: _, factory_context = self.__get_factory_with_context( factory_name ) if handler_id in factory_context.get_handlers_ids(): to_stop.update(self.__get_stored_instances(factory_name)) with self.__instances_lock: for stored_instance in to_stop: # Extract information context = stored_instance.context name = context.name instance = stored_instance.instance # Clean up the stored instance (iPOPO side) del self.__instances[name] stored_instance.kill() # Add the component to the waiting queue self.__waiting_handlers[name] = (context, instance) # Try to find a new handler factory new_ref = self.__context.get_service_reference( handlers_const.SERVICE_IPOPO_HANDLER_FACTORY, "({0}={1})".format(handlers_const.PROP_HANDLER_ID, handler_id), ) if new_ref is not None: self.__add_handler_factory(new_ref)
def __remove_handler_factory(self, svc_ref)
Removes an handler factory :param svc_ref: ServiceReference of the handler factory to remove
3.440784
3.530779
0.974511
# type: (str) -> Tuple[type, FactoryContext] factory = self.__factories.get(factory_name) if factory is None: raise TypeError("Unknown factory '{0}'".format(factory_name)) # Get the factory context factory_context = getattr( factory, constants.IPOPO_FACTORY_CONTEXT, None ) if factory_context is None: raise TypeError( "Factory context missing in '{0}'".format(factory_name) ) return factory, factory_context
def __get_factory_with_context(self, factory_name)
Retrieves the factory registered with the given and its factory context :param factory_name: The name of the factory :return: A (factory, context) tuple :raise TypeError: Unknown factory, or factory not manipulated
3.055065
3.21034
0.951633
# type: (str) -> List[StoredInstance] with self.__instances_lock: return [ stored_instance for stored_instance in self.__instances.values() if stored_instance.factory_name == factory_name ]
def __get_stored_instances(self, factory_name)
Retrieves the list of all stored instances objects corresponding to the given factory name :param factory_name: A factory name :return: All components instantiated from the given factory
2.501078
4.385604
0.570293
# type: (ComponentContext, object) -> bool with self.__instances_lock: # Extract information about the component factory_context = component_context.factory_context handlers_ids = factory_context.get_handlers_ids() name = component_context.name factory_name = factory_context.name try: # Get handlers handler_factories = self.__get_handler_factories(handlers_ids) except KeyError: # A handler is missing, stop here return False # Instantiate the handlers all_handlers = set() # type: Set[Any] for handler_factory in handler_factories: handlers = handler_factory.get_handlers( component_context, instance ) if handlers: all_handlers.update(handlers) # Prepare the stored instance stored_instance = StoredInstance( self, component_context, instance, all_handlers ) # Manipulate the properties for handler in all_handlers: handler.manipulate(stored_instance, instance) # Store the instance self.__instances[name] = stored_instance # Start the manager stored_instance.start() # Notify listeners now that every thing is ready to run self._fire_ipopo_event( constants.IPopoEvent.INSTANTIATED, factory_name, name ) # Try to validate it stored_instance.update_bindings() stored_instance.check_lifecycle() return True
def __try_instantiate(self, component_context, instance)
Instantiates a component, if all of its handlers are there. Returns False if a handler is missing. :param component_context: A ComponentContext bean :param instance: The component instance :return: True if the component has started, False if a handler is missing
4.153017
4.116281
1.008925
# type: (Bundle) -> None with self.__instances_lock: # Prepare the list of components store = self.__auto_restart.setdefault(bundle, []) for stored_instance in self.__instances.values(): # Get the factory name factory = stored_instance.factory_name if self.get_factory_bundle(factory) is bundle: # Factory from this bundle # Test component properties properties = stored_instance.context.properties if properties.get(constants.IPOPO_AUTO_RESTART): # Auto-restart property found store.append( (factory, stored_instance.name, properties) )
def _autorestart_store_components(self, bundle)
Stores the components of the given bundle with the auto-restart property :param bundle: A Bundle object
5.807434
6.49899
0.89359
# type: (Bundle) -> None with self.__instances_lock: instances = self.__auto_restart.get(bundle) if not instances: # Nothing to do return for factory, name, properties in instances: try: # Instantiate the given component self.instantiate(factory, name, properties) except Exception as ex: # Log error, but continue to work _logger.exception( "Error restarting component '%s' ('%s') " "from bundle %s (%d): %s", name, factory, bundle.get_symbolic_name(), bundle.get_bundle_id(), ex, )
def _autorestart_components(self, bundle)
Restart the components of the given bundle :param bundle: A Bundle object
3.8505
4.282031
0.899223
# type: (int, str, Optional[str]) -> None with self.__listeners_lock: # Use a copy of the list of listeners listeners = self.__listeners[:] for listener in listeners: try: listener.handle_ipopo_event( constants.IPopoEvent(kind, factory_name, instance_name) ) except: _logger.exception("Error calling an iPOPO event handler")
def _fire_ipopo_event(self, kind, factory_name, instance_name=None)
Triggers an iPOPO event :param kind: Kind of event :param factory_name: Name of the factory associated to the event :param instance_name: Name of the component instance associated to the event
3.668236
4.248752
0.863368
# type: (dict, dict) -> dict # Normalize given properties if properties is None or not isinstance(properties, dict): properties = {} # Use framework properties to fill missing ones framework = self.__context.get_framework() for property_name in factory_properties: if property_name not in properties: # Missing property value = framework.get_property(property_name) if value is not None: # Set the property value properties[property_name] = value return properties
def _prepare_instance_properties(self, properties, factory_properties)
Prepares the properties of a component instance, based on its configuration, factory and framework properties :param properties: Component instance properties :param factory_properties: Component factory "default" properties :return: The merged properties
3.450987
4.027989
0.856752
# type: (Bundle) -> None # Load the bundle factories factories = _load_bundle_factories(bundle) for context, factory_class in factories: try: # Register each found factory self._register_factory(context.name, factory_class, False) except ValueError as ex: # Already known factory _logger.error( "Cannot register factory '%s' of bundle %d (%s): %s", context.name, bundle.get_bundle_id(), bundle.get_symbolic_name(), ex, ) _logger.error( "class: %s -- module: %s", factory_class, factory_class.__module__, ) else: # Instantiate components for name, properties in context.get_instances().items(): self.instantiate(context.name, name, properties)
def _register_bundle_factories(self, bundle)
Registers all factories found in the given bundle :param bundle: A bundle
3.916682
4.224867
0.927055
# type: (str, type, bool) -> None if not factory_name or not is_string(factory_name): raise ValueError("A factory name must be a non-empty string") if not inspect.isclass(factory): raise TypeError( "Invalid factory class '{0}'".format(type(factory).__name__) ) with self.__factories_lock: if factory_name in self.__factories: if override: _logger.info("Overriding factory '%s'", factory_name) else: raise ValueError( "'{0}' factory already exist".format(factory_name) ) self.__factories[factory_name] = factory # Trigger an event self._fire_ipopo_event( constants.IPopoEvent.REGISTERED, factory_name )
def _register_factory(self, factory_name, factory, override)
Registers a component factory :param factory_name: The name of the factory :param factory: The factory class object :param override: If true, previous factory is overridden, else an exception is risen if a previous factory with that name already exists :raise ValueError: The factory name already exists or is invalid :raise TypeError: Invalid factory type
3.063729
3.160053
0.969518
factories = list(self.__factories.keys()) for factory_name in factories: self.unregister_factory(factory_name)
def _unregister_all_factories(self)
Unregisters all factories. This method should be called only after the iPOPO service has been unregistered (that's why it's not locked)
3.236346
3.325368
0.973229
# type: (Bundle) -> None with self.__factories_lock: # Find out which factories must be removed to_remove = [ factory_name for factory_name in self.__factories if self.get_factory_bundle(factory_name) is bundle ] # Remove all of them for factory_name in to_remove: try: self.unregister_factory(factory_name) except ValueError as ex: _logger.warning( "Error unregistering factory '%s': %s", factory_name, ex )
def _unregister_bundle_factories(self, bundle)
Unregisters all factories of the given bundle :param bundle: A bundle
2.844774
3.250528
0.875173
# Running flag down self.running = False # Unregister the service listener self.__context.remove_service_listener(self) # Clean up handler factories usages with self.__instances_lock: for svc_ref in self._handlers_refs: self.__context.unget_service(svc_ref) self._handlers.clear() self._handlers_refs.clear()
def _stop(self)
iPOPO is stopping: clean everything up
7.059417
6.327908
1.115601
# type: (BundleEvent) -> None kind = event.get_kind() bundle = event.get_bundle() if kind == BundleEvent.STOPPING_PRECLEAN: # A bundle is gone, remove its factories after the deactivator has # been called. That way, the deactivator can kill manually started # components. self._unregister_bundle_factories(bundle) elif kind == BundleEvent.STARTED: # A bundle is staring, register its factories before its activator # is called. That way, the activator can use the registered # factories. self._register_bundle_factories(bundle) elif kind == BundleEvent.UPDATE_BEGIN: # A bundle will be updated, store its auto-restart component self._autorestart_store_components(bundle) elif kind == BundleEvent.UPDATED: # Update has finished, restart stored components self._autorestart_components(bundle) self._autorestart_clear_components(bundle) elif kind == BundleEvent.UPDATE_FAILED: # Update failed, clean the stored components self._autorestart_clear_components(bundle)
def bundle_changed(self, event)
A bundle event has been triggered :param event: The bundle event
4.436141
4.670364
0.949849
# type: (ServiceEvent) -> None # Call sub-methods kind = event.get_kind() svc_ref = event.get_service_reference() if kind == ServiceEvent.REGISTERED: # Service coming with self.__instances_lock: self.__add_handler_factory(svc_ref) elif kind == ServiceEvent.UNREGISTERING: # Service gone with self.__instances_lock: self.__remove_handler_factory(svc_ref)
def service_changed(self, event)
Called when a handler factory service is un/registered
3.88367
3.498863
1.109981
# type: (str, str, dict) -> Any # Test parameters if not factory_name or not is_string(factory_name): raise ValueError("Invalid factory name") if not name or not is_string(name): raise ValueError("Invalid component name") if not self.running: # Stop working if the framework is stopping raise ValueError("Framework is stopping") with self.__instances_lock: if name in self.__instances or name in self.__waiting_handlers: raise ValueError( "'{0}' is an already running instance name".format(name) ) with self.__factories_lock: # Can raise a TypeError exception factory, factory_context = self.__get_factory_with_context( factory_name ) # Check if the factory is singleton and if a component is # already started if ( factory_context.is_singleton and factory_context.is_singleton_active ): raise ValueError( "{0} is a singleton: {1} can't be " "instantiated.".format(factory_name, name) ) # Create component instance try: instance = factory() except Exception: _logger.exception( "Error creating the instance '%s' from factory '%s'", name, factory_name, ) raise TypeError( "Factory '{0}' failed to create '{1}'".format( factory_name, name ) ) # Instantiation succeeded: update singleton status if factory_context.is_singleton: factory_context.is_singleton_active = True # Normalize the given properties properties = self._prepare_instance_properties( properties, factory_context.properties ) # Set up the component instance context component_context = ComponentContext( factory_context, name, properties ) # Try to instantiate the component immediately if not self.__try_instantiate(component_context, instance): # A handler is missing, put the component in the queue self.__waiting_handlers[name] = (component_context, instance) return instance
def instantiate(self, factory_name, name, properties=None)
Instantiates a component from the given factory, with the given name :param factory_name: Name of the component factory :param name: Name of the instance to be started :param properties: Initial properties of the component instance :return: The component instance :raise TypeError: The given factory is unknown :raise ValueError: The given name or factory name is invalid, or an instance with the given name already exists :raise Exception: Something wrong occurred in the factory
3.441111
3.529793
0.974876
# type: (str, dict) -> int with self.__instances_lock: try: stored_instance = self.__instances[name] except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) ) else: return stored_instance.retry_erroneous(properties_update)
def retry_erroneous(self, name, properties_update=None)
Removes the ERRONEOUS state of the given component, and retries a validation :param name: Name of the component to retry :param properties_update: A dictionary to update the initial properties of the component :return: The new state of the component :raise ValueError: Invalid component name
3.612079
4.596103
0.7859
# type: (str) -> None with self.__instances_lock: try: stored_instance = self.__instances[name] except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) ) else: # Call back the component during the invalidation stored_instance.invalidate(True)
def invalidate(self, name)
Invalidates the given component :param name: Name of the component to invalidate :raise ValueError: Invalid component name
5.364851
6.403384
0.837815
# type: (str) -> None if not name: raise ValueError("Name can't be None or empty") with self.__instances_lock: try: # Running instance stored_instance = self.__instances.pop(name) # Store the reference to the factory context factory_context = stored_instance.context.factory_context # Kill it stored_instance.kill() # Update the singleton state flag factory_context.is_singleton_active = False except KeyError: # Queued instance try: # Extract the component context context, _ = self.__waiting_handlers.pop(name) # Update the singleton state flag context.factory_context.is_singleton_active = False except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) )
def kill(self, name)
Kills the given component :param name: Name of the component to kill :raise ValueError: Invalid component name
4.555956
4.640322
0.981819
# type: (BundleContext, type) -> bool if factory is None or bundle_context is None: # Invalid parameter, to nothing raise ValueError("Invalid parameter") context = _set_factory_context(factory, bundle_context) if not context: raise TypeError("Not a manipulated class (no context found)") self._register_factory(context.name, factory, False) return True
def register_factory(self, bundle_context, factory)
Registers a manually created factory, using decorators programmatically :param bundle_context: The factory bundle context :param factory: A manipulated class :return: True if the factory has been registered :raise ValueError: Invalid parameter, or factory already registered :raise TypeError: Invalid factory type (not a manipulated class)
7.301605
6.376735
1.145038
# type: (str) -> bool if not factory_name or not is_string(factory_name): # Invalid name return False with self.__factories_lock: try: # Remove the factory from the registry factory_class = self.__factories.pop(factory_name) except KeyError: # Unknown factory return False # Trigger an event self._fire_ipopo_event( constants.IPopoEvent.UNREGISTERED, factory_name ) # Invalidate and delete all components of this factory with self.__instances_lock: # Compute the list of __instances to remove to_remove = self.__get_stored_instances(factory_name) # Remove instances from the registry: avoids dependencies \ # update to link against a component from this factory again. for instance in to_remove: try: # Kill the instance self.kill(instance.name) except ValueError: # Unknown instance: already killed by the invalidation # callback of a component killed in this loop # => ignore pass # Remove waiting component names = [ name for name, (context, _) in self.__waiting_handlers.items() if context.factory_context.name == factory_name ] for name in names: del self.__waiting_handlers[name] # Clear the bundle context of the factory _set_factory_context(factory_class, None) return True
def unregister_factory(self, factory_name)
Unregisters the given component factory :param factory_name: Name of the factory to unregister :return: True the factory has been removed, False if the factory is unknown
5.823704
5.840294
0.997159
# type: () -> List[Tuple[str, str, int]] with self.__instances_lock: return sorted( (name, stored_instance.factory_name, stored_instance.state) for name, stored_instance in self.__instances.items() )
def get_instances(self)
Retrieves the list of the currently registered component instances :return: A list of (name, factory name, state) tuples.
4.612134
4.122672
1.118725
# type: () -> List[Tuple[str, str, Set[str]]] with self.__instances_lock: result = [] for name, (context, _) in self.__waiting_handlers.items(): # Compute missing handlers missing = set(context.factory_context.get_handlers_ids()) missing.difference_update(self._handlers.keys()) result.append((name, context.factory_context.name, missing)) result.sort() return result
def get_waiting_components(self)
Returns the list of the instances waiting for their handlers :return: A list of (name, factory name, missing handlers) tuples
4.973871
4.173401
1.191803
# type: (str) -> Dict[str, Any] if not is_string(name): raise ValueError("Component name must be a string") with self.__instances_lock: if name not in self.__instances: raise ValueError("Unknown component: {0}".format(name)) stored_instance = self.__instances[name] assert isinstance(stored_instance, StoredInstance) with stored_instance._lock: result = {} # type: Dict[str, Any] result["name"] = stored_instance.name # Factory name result["factory"] = stored_instance.factory_name # Factory bundle result[ "bundle_id" ] = stored_instance.bundle_context.get_bundle().get_bundle_id() # Component state result["state"] = stored_instance.state # Error details result["error_trace"] = stored_instance.error_trace # Provided service result["services"] = {} for handler in stored_instance.get_handlers( handlers_const.KIND_SERVICE_PROVIDER ): svc_ref = handler.get_service_reference() if svc_ref is not None: svc_id = svc_ref.get_property(SERVICE_ID) result["services"][svc_id] = svc_ref # Dependencies result["dependencies"] = {} for dependency in stored_instance.get_handlers( handlers_const.KIND_DEPENDENCY ): # Dependency info = result["dependencies"][dependency.get_field()] = {} info["handler"] = type(dependency).__name__ # Requirement req = dependency.requirement info["specification"] = req.specification info["filter"] = str(req.filter) if req.filter else None info["optional"] = req.optional info["aggregate"] = req.aggregate # Bindings info["bindings"] = dependency.get_bindings() # Properties properties = stored_instance.context.properties.items() result["properties"] = { str(key): str(value) for key, value in properties } # All done return result
def get_instance_details(self, name)
Retrieves a snapshot of the given component instance. The result dictionary has the following keys: * ``name``: The component name * ``factory``: The name of the component factory * ``bundle_id``: The ID of the bundle providing the component factory * ``state``: The current component state * ``services``: A ``{Service ID → Service reference}`` dictionary, with all services provided by the component * ``dependencies``: A dictionary associating field names with the following dictionary: * ``handler``: The name of the type of the dependency handler * ``filter`` (optional): The requirement LDAP filter * ``optional``: A flag indicating whether the requirement is optional or not * ``aggregate``: A flag indicating whether the requirement is a set of services or not * ``binding``: A list of the ServiceReference the component is bound to * ``properties``: A dictionary key → value, with all properties of the component. The value is converted to its string representation, to avoid unexpected behaviours. :param name: The name of a component instance :return: A dictionary of details :raise ValueError: Invalid component name
2.866109
2.531624
1.132123
# type: (str) -> Bundle with self.__factories_lock: try: factory = self.__factories[name] except KeyError: raise ValueError("Unknown factory '{0}'".format(name)) else: # Bundle Context is stored in the Factory Context factory_context = getattr( factory, constants.IPOPO_FACTORY_CONTEXT ) return factory_context.bundle_context.get_bundle()
def get_factory_bundle(self, name)
Retrieves the Pelix Bundle object that registered the given factory :param name: The name of a factory :return: The Bundle that registered the given factory :raise ValueError: Invalid factory
4.991797
5.250251
0.950773
# type: (str) -> Dict[str, Any] with self.__factories_lock: try: factory = self.__factories[name] except KeyError: raise ValueError("Unknown factory '{0}'".format(name)) context = getattr(factory, constants.IPOPO_FACTORY_CONTEXT) assert isinstance(context, FactoryContext) result = {} # type: Dict[Any, Any] # Factory name & bundle result["name"] = context.name result["bundle"] = context.bundle_context.get_bundle() # Configurable properties # Name -> Default value result["properties"] = { prop_name: context.properties.get(prop_name) for prop_name in context.properties_fields.values() } # Requirements (list of dictionaries) reqs = result["requirements"] = [] handler_requires = context.get_handler(constants.HANDLER_REQUIRES) if handler_requires is not None: for field, requirement in handler_requires.items(): reqs.append( { "id": field, "specification": requirement.specification, "aggregate": requirement.aggregate, "optional": requirement.optional, "filter": requirement.original_filter, } ) # Provided services (list of list of specifications) handler_provides = context.get_handler(constants.HANDLER_PROVIDES) if handler_provides is not None: result["services"] = [ specs_controller[0] for specs_controller in handler_provides ] else: result["services"] = [] # Other handlers handlers = set(context.get_handlers_ids()) handlers.difference_update( ( constants.HANDLER_PROPERTY, constants.HANDLER_PROVIDES, constants.HANDLER_REQUIRES, ) ) result["handlers"] = { handler: copy.deepcopy(context.get_handler(handler)) for handler in handlers } return result
def get_factory_details(self, name)
Retrieves a dictionary with details about the given factory * ``name``: The factory name * ``bundle``: The Bundle object of the bundle providing the factory * ``properties``: Copy of the components properties defined by the factory * ``requirements``: List of the requirements defined by the factory * ``id``: Requirement ID (field where it is injected) * ``specification``: Specification of the required service * ``aggregate``: If True, multiple services will be injected * ``optional``: If True, the requirement is optional * ``services``: List of the specifications of the services provided by components of this factory * ``handlers``: Dictionary of the non-built-in handlers required by this factory. The dictionary keys are handler IDs, and it contains a tuple with: * A copy of the configuration of the handler (0) * A flag indicating if the handler is present or not :param name: The name of a factory :return: A dictionary describing the factory :raise ValueError: Invalid factory
3.14904
2.939842
1.07116
# type: (socket.socket, bool) -> None try: # Use existing value opt_ipv6_only = socket.IPV6_V6ONLY except AttributeError: # Use "known" value if os.name == "nt": # Windows: see ws2ipdef.h opt_ipv6_only = 27 elif platform.system() == "Linux": # Linux: see linux/in6.h (in recent kernels) opt_ipv6_only = 26 else: # Unknown value: do nothing raise # Setup the socket (can raise a socket.error) socket_obj.setsockopt(ipproto_ipv6(), opt_ipv6_only, int(not double_stack))
def set_double_stack(socket_obj, double_stack=True)
Sets up the IPv6 double stack according to the operating system :param socket_obj: A socket object :param double_stack: If True, use the double stack, else only support IPv6 :raise AttributeError: Python or system doesn't support V6 :raise socket.error: Error setting up the double stack value
5.307607
5.550122
0.956305
# type: (str) -> str # pylint: disable=C0103 if not ldap_string: # No content return ldap_string # Protect escape character previously in the string assert is_string(ldap_string) ldap_string = ldap_string.replace( ESCAPE_CHARACTER, ESCAPE_CHARACTER + ESCAPE_CHARACTER ) # Leading space if ldap_string.startswith(" "): ldap_string = "\\ {0}".format(ldap_string[1:]) # Trailing space if ldap_string.endswith(" "): ldap_string = "{0}\\ ".format(ldap_string[:-1]) # Escape other characters for escaped in ESCAPED_CHARACTERS: ldap_string = ldap_string.replace(escaped, ESCAPE_CHARACTER + escaped) return ldap_string
def escape_LDAP(ldap_string)
Escape a string to let it go in an LDAP filter :param ldap_string: The string to escape :return: The protected string
2.691874
2.905829
0.92637
# type: (str) -> str # pylint: disable=C0103 if ldap_string is None: return None if ESCAPE_CHARACTER not in ldap_string: # No need to loop return ldap_string escaped = False result = "" for character in ldap_string: if not escaped and character == ESCAPE_CHARACTER: # Escape character found escaped = True else: # Copy the character escaped = False result += character return result
def unescape_LDAP(ldap_string)
Unespaces an LDAP string :param ldap_string: The string to unescape :return: The unprotected string
3.23255
3.690176
0.875988
# The filter value is a joker : simple presence test if tested_value is None: return False elif hasattr(tested_value, "__len__"): # Refuse empty values # pylint: disable=C1801 return len(tested_value) != 0 # Presence validated return True
def _comparator_presence(_, tested_value)
Tests a filter which simply a joker, i.e. a value presence test
8.865952
7.021672
1.262655
if isinstance(tested_value, ITERABLES): for value in tested_value: if _star_comparison(filter_value, value): return True return False return _star_comparison(filter_value, tested_value)
def _comparator_star(filter_value, tested_value)
Tests a filter containing a joker
3.045857
3.097825
0.983225
if not is_string(tested_value): # Unhandled value type... return False parts = filter_value.split("*") i = 0 last_part = len(parts) - 1 idx = 0 for part in parts: # Find the part in the tested value idx = tested_value.find(part, idx) if idx == -1: # Part not found return False len_part = len(part) if i == 0 and len_part != 0 and idx != 0: # First part is not a star, but the tested value is not at # position 0 => Doesn't match return False if ( i == last_part and len_part != 0 and idx != len(tested_value) - len_part ): # Last tested part is not at the end of the sequence return False # Be sure to test the next part idx += len_part i += 1 # Whole test passed return True
def _star_comparison(filter_value, tested_value)
Tests a filter containing a joker
3.304603
3.317091
0.996235
if isinstance(tested_value, ITERABLES): # Convert the list items to strings for value in tested_value: # Try with the string conversion if not is_string(value): value = repr(value) if filter_value == value: # Match ! return True # Standard comparison elif not is_string(tested_value): # String vs string representation return filter_value == repr(tested_value) else: # String vs string return filter_value == tested_value return False
def _comparator_eq(filter_value, tested_value)
Tests if the filter value is equal to the tested value
4.638264
4.597248
1.008922
lower_filter_value = filter_value.lower() if is_string(tested_value): # Lower case comparison return _comparator_eq(lower_filter_value, tested_value.lower()) elif hasattr(tested_value, "__iter__"): # Extract a list of strings new_tested = [ value.lower() for value in tested_value if is_string(value) ] if _comparator_eq(lower_filter_value, new_tested): # Value found in the strings return True # Compare the raw values return _comparator_eq(filter_value, tested_value) or _comparator_eq( lower_filter_value, tested_value )
def _comparator_approximate(filter_value, tested_value)
Tests if the filter value is nearly equal to the tested value. If the tested value is a string or an array of string, it compares their lower case forms
3.322306
3.174256
1.046641
lower_filter_value = filter_value.lower() if is_string(tested_value): # Lower case comparison return _comparator_star(lower_filter_value, tested_value.lower()) elif hasattr(tested_value, "__iter__"): # Extract a list of strings new_tested = [ value.lower() for value in tested_value if is_string(value) ] if _comparator_star(lower_filter_value, new_tested): # Value found in the strings return True # Compare the raw values return _comparator_star(filter_value, tested_value) or _comparator_star( lower_filter_value, tested_value )
def _comparator_approximate_star(filter_value, tested_value)
Tests if the filter value, which contains a joker, is nearly equal to the tested value. If the tested value is a string or an array of string, it compares their lower case forms
3.301852
3.161613
1.044357
if is_string(filter_value): value_type = type(tested_value) try: # Try a conversion filter_value = value_type(filter_value) except (TypeError, ValueError): if value_type is int: # Integer/float comparison trick try: filter_value = float(filter_value) except (TypeError, ValueError): # None-float value return False else: # Incompatible type return False try: return tested_value < filter_value except TypeError: # Incompatible type return False
def _comparator_lt(filter_value, tested_value)
Tests if the filter value is strictly greater than the tested value tested_value < filter_value
3.498955
3.508632
0.997242
# type: (str, int) -> Optional[Callable[[Any, Any], bool]] part1 = string[idx] try: part2 = string[idx + 1] except IndexError: # String is too short (no comparison) return None if part1 == "=": # Equality return _comparator_eq elif part2 != "=": # It's a "strict" operator if part1 == "<": # Strictly lesser return _comparator_lt elif part1 == ">": # Strictly greater return _comparator_gt else: if part1 == "<": # Less or equal return _comparator_le elif part1 == ">": # Greater or equal return _comparator_ge elif part1 == "~": # Approximate equality return _comparator_approximate return None
def _compute_comparator(string, idx)
Tries to compute the LDAP comparator at the given index Valid operators are : * = : equality * <= : less than * >= : greater than * ~= : approximate :param string: A LDAP filter string :param idx: An index in the given string :return: The corresponding operator, None if unknown
2.863128
3.006318
0.95237
# type: (str, int) -> Optional[int] operator = string[idx] if operator == "&": return AND elif operator == "|": return OR elif operator == "!": return NOT return None
def _compute_operation(string, idx)
Tries to compute the LDAP operation at the given index Valid operations are : * & : AND * | : OR * ! : NOT :param string: A LDAP filter string :param idx: An index in the given string :return: The corresponding operator (AND, OR or NOT)
3.390552
4.256287
0.796599
# type: (str, int) -> int i = idx for char in string[idx:]: if not char.isspace(): return i i += 1 return -1
def _skip_spaces(string, idx)
Retrieves the next non-space character after idx index in the given string :param string: The string to look into :param idx: The base search index :return: The next non-space character index, -1 if not found
3.063141
4.370237
0.70091
# type: (str, int, int) -> LDAPCriteria comparators = "=<>~" if startidx < 0: raise ValueError( "Invalid string range start={0}, end={1}".format(startidx, endidx) ) # Get the comparator escaped = False idx = startidx for char in ldap_filter[startidx:endidx]: if not escaped: if char == ESCAPE_CHARACTER: # Next character escaped escaped = True elif char in comparators: # Comparator found break else: # Escaped character ignored escaped = False idx += 1 else: # Comparator never found raise ValueError( "Comparator not found in '{0}'".format(ldap_filter[startidx:endidx]) ) # The attribute name can be extracted directly attribute_name = ldap_filter[startidx:idx].strip() if not attribute_name: # Attribute name is missing raise ValueError( "Attribute name is missing in '{0}'".format( ldap_filter[startidx:endidx] ) ) comparator = _compute_comparator(ldap_filter, idx) if comparator is None: # Unknown comparator raise ValueError( "Unknown comparator in '{0}' - {1}\nFilter : {2}".format( ldap_filter[startidx:endidx], ldap_filter[idx], ldap_filter ) ) # Find the end of the comparator while ldap_filter[idx] in comparators: idx += 1 # Skip spaces idx = _skip_spaces(ldap_filter, idx) # Extract the value value = ldap_filter[idx:endidx].strip() # Use the appropriate comparator if a joker is found in the filter value if value == "*": # Presence comparator comparator = _comparator_presence elif "*" in value: # Joker if comparator == _comparator_eq: comparator = _comparator_star elif comparator == _comparator_approximate: comparator = _comparator_approximate_star return LDAPCriteria( unescape_LDAP(attribute_name), unescape_LDAP(value), comparator )
def _parse_ldap_criteria(ldap_filter, startidx=0, endidx=-1)
Parses an LDAP sub filter (criterion) :param ldap_filter: An LDAP filter string :param startidx: Sub-filter start index :param endidx: Sub-filter end index :return: The LDAP sub-filter :raise ValueError: Invalid sub-filter
3.164137
3.321936
0.952498
# type: (str) -> Optional[LDAPFilter] if ldap_filter is None: # Nothing to do return None assert is_string(ldap_filter) # Remove surrounding spaces ldap_filter = ldap_filter.strip() if not ldap_filter: # Empty string return None escaped = False filter_len = len(ldap_filter) root = None stack = [] subfilter_stack = [] idx = 0 while idx < filter_len: if not escaped: if ldap_filter[idx] == "(": # Opening filter : get the operator idx = _skip_spaces(ldap_filter, idx + 1) if idx == -1: raise ValueError( "Missing filter operator: {0}".format(ldap_filter) ) operator = _compute_operation(ldap_filter, idx) if operator is not None: # New sub-filter stack.append(LDAPFilter(operator)) else: # Sub-filter content subfilter_stack.append(idx) elif ldap_filter[idx] == ")": # Ending filter : store it in its parent if subfilter_stack: # criterion finished start_idx = subfilter_stack.pop() criterion = _parse_ldap_criteria( ldap_filter, start_idx, idx ) if stack: top = stack.pop() top.append(criterion) stack.append(top) else: # No parent : filter contains only one criterion # Make a parent to stay homogeneous root = LDAPFilter(AND) root.append(criterion) elif stack: # Sub filter finished ended_filter = stack.pop() if stack: top = stack.pop() top.append(ended_filter) stack.append(top) else: # End of the parse root = ended_filter else: raise ValueError( "Too many end of parenthesis:{0}: {1}".format( idx, ldap_filter[idx:] ) ) elif ldap_filter[idx] == "\\": # Next character must be ignored escaped = True else: # Escaped character ignored escaped = False # Don't forget to increment... idx += 1 # No root : invalid content if root is None: raise ValueError("Invalid filter string: {0}".format(ldap_filter)) # Return the root of the filter return root.normalize()
def _parse_ldap(ldap_filter)
Parses the given LDAP filter string :param ldap_filter: An LDAP filter string :return: An LDAPFilter object, None if the filter was empty :raise ValueError: The LDAP filter string is invalid
3.366084
3.424771
0.982864
# type: (Any) -> Optional[Union[LDAPFilter, LDAPCriteria]] if ldap_filter is None: return None if isinstance(ldap_filter, (LDAPFilter, LDAPCriteria)): # No conversion needed return ldap_filter elif is_string(ldap_filter): # Parse the filter return _parse_ldap(ldap_filter) # Unknown type raise TypeError( "Unhandled filter type {0}".format(type(ldap_filter).__name__) )
def get_ldap_filter(ldap_filter)
Retrieves the LDAP filter object corresponding to the given filter. Parses it the argument if it is an LDAPFilter instance :param ldap_filter: An LDAP filter (LDAPFilter or string) :return: The corresponding filter, can be None :raise ValueError: Invalid filter string found :raise TypeError: Unknown filter type
3.57695
3.963409
0.902493
# type: (Iterable[Any], int) -> Optional[Union[LDAPFilter, LDAPCriteria]] if not filters: return None if not hasattr(filters, "__iter__") or is_string(filters): raise TypeError("Filters argument must be iterable") # Remove None filters and convert others ldap_filters = [] for sub_filter in filters: if sub_filter is None: # Ignore None filters continue ldap_filter = get_ldap_filter(sub_filter) if ldap_filter is not None: # Valid filter ldap_filters.append(ldap_filter) if not ldap_filters: # Do nothing return None elif len(ldap_filters) == 1: # Only one filter, return it return ldap_filters[0] new_filter = LDAPFilter(operator) for sub_filter in ldap_filters: # Direct combination new_filter.append(sub_filter) return new_filter.normalize()
def combine_filters(filters, operator=AND)
Combines two LDAP filters, which can be strings or LDAPFilter objects :param filters: Filters to combine :param operator: The operator for combination :return: The combined filter, can be None if all filters are None :raise ValueError: Invalid filter string found :raise TypeError: Unknown filter type
3.209287
3.380506
0.949351
if not isinstance(ldap_filter, (LDAPFilter, LDAPCriteria)): raise TypeError( "Invalid filter type: {0}".format(type(ldap_filter).__name__) ) if len(self.subfilters) >= 1 and self.operator == NOT: raise ValueError("Not operator only handles one child") self.subfilters.append(ldap_filter)
def append(self, ldap_filter)
Appends a filter or a criterion to this filter :param ldap_filter: An LDAP filter or criterion :raise TypeError: If the parameter is not of a known type :raise ValueError: If the more than one filter is associated to a NOT operator
4.377407
3.56479
1.227956
# Use a generator, and declare it outside of the method call # => seems to be quite a speed up trick generator = ( criterion.matches(properties) for criterion in self.subfilters ) # Extract "if" from loops and use built-in methods if self.operator == OR: result = any(generator) else: result = all(generator) if self.operator == NOT: # Revert result return not result return result
def matches(self, properties)
Tests if the given properties matches this LDAP filter and its children :param properties: A dictionary of properties :return: True if the properties matches this filter, else False
11.531102
11.248003
1.025169
if not self.subfilters: # No sub-filters return None # New sub-filters list new_filters = [] for subfilter in self.subfilters: # Normalize the sub-filter before storing it norm_filter = subfilter.normalize() if norm_filter is not None and norm_filter not in new_filters: new_filters.append(norm_filter) # Update the instance self.subfilters = new_filters size = len(self.subfilters) if size > 1 or self.operator == NOT: # Normal filter or NOT # NOT is the only operator to accept 1 operand return self # Return the only child as the filter object return self.subfilters[0].normalize()
def normalize(self)
Returns the first meaningful object in this filter.
4.499586
4.161824
1.081157
try: # Use the comparator return self.comparator(self.value, properties[self.name]) except KeyError: # Criterion key is not in the properties return False
def matches(self, properties)
Tests if the given criterion matches this LDAP criterion :param properties: A dictionary of properties :return: True if the properties matches this criterion, else False
6.143498
5.686286
1.080406
# Create the framework framework = pelix.framework.create_framework( ( "pelix.ipopo.core", "pelix.ipopo.waiting", # Shell "pelix.shell.core", "pelix.shell.ipopo", "pelix.shell.console", # HTTP Service "pelix.http.basic", # Remote Services (core) "pelix.remote.dispatcher", "pelix.remote.registry", ), # Framework properties {pelix.constants.FRAMEWORK_UID: other_arguments.fw_uid}, ) # Start everything framework.start() context = framework.get_bundle_context() # Instantiate components # Get the iPOPO service with use_waiting_list(context) as ipopo: # Instantiate remote service components # ... HTTP server ipopo.add( "pelix.http.service.basic.factory", "http-server", {"pelix.http.address": "0.0.0.0", "pelix.http.port": http_port}, ) # ... servlet giving access to the registry ipopo.add( rs.FACTORY_REGISTRY_SERVLET, "pelix-remote-dispatcher-servlet" ) # Prepare the utility object util = InstallUtils(context, other_arguments) # Install the discovery bundles for discovery in discoveries: getattr(util, "discovery_{0}".format(discovery))() # Install the transport bundles for transport in transports: getattr(util, "transport_{0}".format(transport))() # Start the service provider or consumer if is_server: # ... the provider context.install_bundle("remote.provider").start() else: # ... or the consumer context.install_bundle("remote.consumer").start() # Start the framework and wait for it to stop framework.wait_for_stop()
def main(is_server, discoveries, transports, http_port, other_arguments)
Runs the framework :param is_server: If True, starts the provider bundle, else the consumer one :param discoveries: List of discovery protocols :param transports: List of RPC protocols :param http_port: Port of the HTTP server :param other_arguments: Other arguments
3.881514
3.782553
1.026162
# Install the bundle self.context.install_bundle("pelix.remote.discovery.multicast").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_MULTICAST, "pelix-discovery-multicast" )
def discovery_multicast(self)
Installs the multicast discovery bundles and instantiates components
10.10816
8.745319
1.155837
# Remove Zeroconf debug output logging.getLogger("zeroconf").setLevel(logging.WARNING) # Install the bundle self.context.install_bundle("pelix.remote.discovery.mdns").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add(rs.FACTORY_DISCOVERY_ZEROCONF, "pelix-discovery-zeroconf")
def discovery_mdns(self)
Installs the mDNS discovery bundles and instantiates components
10.335804
9.40064
1.099479
# Install the bundle self.context.install_bundle("pelix.remote.discovery.mqtt").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_MQTT, "pelix-discovery-mqtt", { "application.id": "sample.rs", "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, )
def discovery_mqtt(self)
Installs the MQTT discovery bundles and instantiates components
7.224279
6.61404
1.092264
# Install the bundle self.context.install_bundle("pelix.remote.discovery.redis").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_REDIS, "pelix-discovery-redis", { "application.id": "sample.rs", "redis.host": self.arguments.redis_host, "redis.port": self.arguments.redis_port, }, )
def discovery_redis(self)
Installs the Redis discovery bundles and instantiates components
7.173604
6.631429
1.081758
# Install the bundle self.context.install_bundle("pelix.remote.discovery.zookeeper").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_ZOOKEEPER, "pelix-discovery-zookeeper", { "application.id": "sample.rs", "zookeeper.hosts": self.arguments.zk_hosts, "zookeeper.prefix": self.arguments.zk_prefix, }, )
def discovery_zookeeper(self)
Installs the ZooKeeper discovery bundles and instantiates components
7.101761
6.768317
1.049265
# Install the bundle self.context.install_bundle("pelix.remote.json_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_JSONRPC_EXPORTER, "pelix-jsonrpc-exporter" ) ipopo.add( rs.FACTORY_TRANSPORT_JSONRPC_IMPORTER, "pelix-jsonrpc-importer" )
def transport_jsonrpc(self)
Installs the JSON-RPC transport bundles and instantiates components
6.765929
6.029908
1.122062
# Install the bundle self.context.install_bundle( "pelix.remote.transport.jabsorb_rpc" ).start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_JABSORBRPC_EXPORTER, "pelix-jabsorbrpc-exporter", ) ipopo.add( rs.FACTORY_TRANSPORT_JABSORBRPC_IMPORTER, "pelix-jabsorbrpc-importer", )
def transport_jabsorbrpc(self)
Installs the JABSORB-RPC transport bundles and instantiates components
5.017532
4.649197
1.079225
# Install the bundle self.context.install_bundle("pelix.remote.transport.mqtt_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_MQTTRPC_EXPORTER, "pelix-mqttrpc-exporter", { "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, ) ipopo.add( rs.FACTORY_TRANSPORT_MQTTRPC_IMPORTER, "pelix-mqttrpc-importer", { "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, )
def transport_mqttrpc(self)
Installs the MQTT-RPC transport bundles and instantiates components
3.396782
3.151327
1.07789
# Install the bundle self.context.install_bundle("pelix.remote.xml_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_XMLRPC_EXPORTER, "pelix-xmlrpc-exporter" ) ipopo.add( rs.FACTORY_TRANSPORT_XMLRPC_IMPORTER, "pelix-xmlrpc-importer" )
def transport_xmlrpc(self)
Installs the XML-RPC transport bundles and instantiates components
6.510721
5.85851
1.111327
# Extract information from the context requirements = component_context.get_handler( ipopo_constants.HANDLER_REQUIRES_BEST ) 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 return [ BestDependency(field, requirement) for field, requirement in requirements.items() ]
def get_handlers(self, component_context, instance)
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component
6.977404
7.49085
0.931457
with self._lock: new_ranking = svc_ref.get_property(SERVICE_RANKING) if self._current_ranking is not None: if new_ranking > self._current_ranking: # New service with better ranking: use it self._pending_ref = svc_ref old_ref = self.reference old_value = self._value # Clean up like for a departure self._current_ranking = None self._value = None self.reference = None # Unbind (new binding will be done afterwards) self._ipopo_instance.unbind(self, old_value, old_ref) else: # No ranking yet: inject the service self.reference = svc_ref self._value = self._context.get_service(svc_ref) self._current_ranking = new_ranking self._pending_ref = None self._ipopo_instance.bind(self, self._value, self.reference)
def on_service_arrival(self, svc_ref)
Called when a service has been registered in the framework :param svc_ref: A service reference
3.911735
4.120366
0.949366
with self._lock: if svc_ref is self.reference: # Injected service going away... service = self._value # Clear the instance values self._current_ranking = None self._value = None self.reference = None if self.requirement.immediate_rebind: # Look for a replacement self._pending_ref = self._context.get_service_reference( self.requirement.specification, self.requirement.filter ) else: self._pending_ref = None self._ipopo_instance.unbind(self, service, svc_ref)
def on_service_departure(self, svc_ref)
Called when a service has been unregistered from the framework :param svc_ref: A service reference
7.390048
8.355138
0.884491
with self._lock: if self.reference is None: # A previously registered service now matches our filter return self.on_service_arrival(svc_ref) else: # Check if the ranking changed the service to inject best_ref = self._context.get_service_reference( self.requirement.specification, self.requirement.filter ) if best_ref is self.reference: # Still the best service: notify the property modification if svc_ref is self.reference: # Call update only if necessary self._ipopo_instance.update( self, self._value, svc_ref, old_properties ) else: # A new service is now the best: start a departure loop self.on_service_departure(self.reference) 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
7.965253
8.708078
0.914697
with self.__lock: if self.__deleted: raise ValueError("{0} has been deleted".format(self.__pid)) elif not self.__updated: # Fresh configuration return None # Filter a copy of the properties props = self.__properties.copy() try: del props[services.CONFIG_PROP_BUNDLE_LOCATION] except KeyError: # Ignore pass return props
def get_properties(self)
Return the properties of this Configuration object. The Dictionary object returned is a private copy for the caller and may be changed without influencing the stored configuration. If called just after the configuration is created and before update has been called, this method returns None. :return: A private copy of the properties for the caller or null. These properties must not contain the "service.bundleLocation" property. The value of this property may be obtained from the get_bundle_location() method.
7.494636
5.442587
1.377036
if not properties: # Nothing to do return False with self.__lock: # Make a copy of the properties properties = properties.copy() # Override properties properties[services.CONFIG_PROP_PID] = self.__pid if self.__location: properties[ services.CONFIG_PROP_BUNDLE_LOCATION ] = self.__location if self.__factory_pid: properties[ services.CONFIG_PROP_FACTORY_PID ] = self.__factory_pid # See if new properties are different if properties == self.__properties: return False # Store the copy (before storing data) self.__properties = properties self.__updated = True # Store the data # it will cause FileInstall to update this configuration again, but # this will ignored because self.__properties has already been # saved self.__persistence.store(self.__pid, properties) return True
def __properties_update(self, properties)
Internal update of configuration properties. Does not notifies the ConfigurationAdmin of this modification. :param properties: the new set of properties for this configuration :return: True if the properties have been updated, else False
5.550307
5.055037
1.097976
# pylint: disable=W0212 with self.__lock: # Update properties if self.__properties_update(properties): # Update configurations, if something changed self.__config_admin._update(self)
def update(self, properties=None)
If called without properties, only notifies listeners Update the properties of this Configuration object. Stores the properties in persistent storage after adding or overwriting the following properties: * "service.pid" : is set to be the PID of this configuration. * "service.factoryPid" : if this is a factory configuration it is set to the factory PID else it is not set. These system properties are all of type String. If the corresponding Managed Service/Managed Service Factory is registered, its updated method must be called asynchronously. Else, this callback is delayed until aforementioned registration occurs. Also initiates an asynchronous call to all ConfigurationListeners with a ConfigurationEvent.CM_UPDATED event. :param properties: the new set of properties for this configuration :raise IOError: Error storing the configuration
9.88884
12.703237
0.77845
# pylint: disable=W0212 with self.__lock: if self.__deleted: # Nothing to do return # Update status self.__deleted = True # Notify ConfigurationAdmin, notify services only if the # configuration had been updated before self.__config_admin._delete(self, self.__updated, directory_updated) # Remove the file self.__persistence.delete(self.__pid) # Clean up if self.__properties: self.__properties.clear() self.__persistence = None self.__pid = None
def delete(self, directory_updated=False)
Delete this configuration :param directory_updated: If True, tell ConfigurationAdmin to not recall the directory of this deletion (internal use only)
6.510032
5.705095
1.141091
if not self.is_valid(): # Do not test invalid configurations return False return ldap_filter.matches(self.__properties)
def matches(self, ldap_filter)
Tests if this configuration matches the given filter. :param ldap_filter: A parsed LDAP filter object :return: True if the properties of this configuration matches the filter
10.181251
8.763325
1.161802
if path is None or not os.path.isdir(path): return yielded = set() try: file_names = os.listdir(path) except OSError: # ignore unreadable directories like import does file_names = [] # handle packages before same-named modules file_names.sort() for filename in file_names: modname = inspect.getmodulename(filename) if modname == "__init__" or modname in yielded: continue file_path = os.path.join(path, filename) is_package = False if not modname and os.path.isdir(file_path) and "." not in filename: modname = filename try: dir_contents = os.listdir(file_path) except OSError: # ignore unreadable directories like import does dir_contents = [] for sub_filename in dir_contents: sub_name = inspect.getmodulename(sub_filename) if sub_name == "__init__": is_package = True break else: # not a package continue if modname and "." not in modname: yielded.add(modname) yield modname, is_package
def walk_modules(path)
Code from ``pkgutil.ImpImporter.iter_modules()``: walks through a folder and yields all loadable packages and modules. :param path: Path where to look for modules :return: Generator to walk through found packages and modules
2.498068
2.569459
0.972216
# type: (Union[list, tuple], dict, bool, bool, bool) -> Framework # Test if a framework already exists if FrameworkFactory.is_framework_running(None): raise ValueError("A framework is already running") # Create the framework framework = FrameworkFactory.get_framework(properties) # Install bundles context = framework.get_bundle_context() for bundle in bundles: context.install_bundle(bundle) if auto_start: # Automatically start the framework framework.start() if wait_for_stop: # Wait for the framework to stop try: framework.wait_for_stop(None) except KeyboardInterrupt: # Stop keyboard interruptions if framework.get_state() == Bundle.ACTIVE: framework.stop() if auto_delete: # Delete the framework FrameworkFactory.delete_framework(framework) framework = None return framework
def create_framework( bundles, properties=None, auto_start=False, wait_for_stop=False, auto_delete=False, )
Creates a Pelix framework, installs the given bundles and returns its instance reference. If *auto_start* is True, the framework will be started once all bundles will have been installed If *wait_for_stop* is True, the method will return only when the framework will have stopped. This requires *auto_start* to be True. If *auto_delete* is True, the framework will be deleted once it has stopped, and the method will return None. This requires *wait_for_stop* and *auto_start* to be True. :param bundles: Bundles to initially install (shouldn't be empty if *wait_for_stop* is True) :param properties: Optional framework properties :param auto_start: If True, the framework will be started immediately :param wait_for_stop: If True, the method will return only when the framework will have stopped :param auto_delete: If True, deletes the framework once it stopped. :return: The framework instance :raise ValueError: Only one framework can run at a time
2.710657
2.691851
1.006987
# type: (str) -> bool while path: if os.path.exists(path): return True else: path = os.path.dirname(path) return False
def _package_exists(path)
Checks if the given Python path matches a valid file or a valid container file :param path: A Python path :return: True if the module or its container exists
2.752633
4.571786
0.602091
# Normalize Python paths whole_path = [ os.path.abspath(path) for path in sys.path if os.path.exists(path) ] # Keep the "dynamic" current folder indicator and add the "static" # current path # Use an OrderedDict to have a faster lookup (path not in whole_set) whole_set = collections.OrderedDict((("", 1), (os.getcwd(), 1))) # Add original path entries for path in whole_path: if path not in whole_set: whole_set[path] = 1 # Set the new content of sys.path (still ordered thanks to OrderedDict) sys.path = list(whole_set) # Normalize paths in loaded modules for module_ in sys.modules.values(): try: module_.__path__ = [ os.path.abspath(path) for path in module_.__path__ if _package_exists(path) ] except AttributeError: # builtin modules don't have a __path__ pass except ImportError: pass
def normalize_path()
Normalizes sys.path to avoid the use of relative folders
5.05367
4.869442
1.037834
# Get the activator activator = getattr(self.__module, ACTIVATOR, None) if activator is None: # Get the old activator activator = getattr(self.__module, ACTIVATOR_LEGACY, None) if activator is not None: # Old activator found: print a deprecation warning _logger.warning( "Bundle %s uses the deprecated '%s' to declare" " its activator. Use @BundleActivator instead.", self.__name, ACTIVATOR_LEGACY, ) return getattr(activator, method_name, None)
def __get_activator_method(self, method_name)
Retrieves the requested method of the activator, or returns None :param method_name: A method name :return: A method, or None
3.869448
4.005348
0.966071
# type: (int) -> None self.__framework._dispatcher.fire_bundle_event(BundleEvent(kind, self))
def _fire_bundle_event(self, kind)
Fires a bundle event of the given kind :param kind: Kind of event
7.919173
13.788973
0.574312
# type: () -> List[ServiceReference] if self._state == Bundle.UNINSTALLED: raise BundleException( "Can't call 'get_registered_services' on an " "uninstalled bundle" ) return self.__framework._registry.get_bundle_registered_services(self)
def get_registered_services(self)
Returns this bundle's ServiceReference list for all services it has registered or an empty list The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled
4.911635
5.324452
0.922468
# type: () -> List[ServiceReference] if self._state == Bundle.UNINSTALLED: raise BundleException( "Can't call 'get_services_in_use' on an uninstalled bundle" ) return self.__framework._registry.get_bundle_imported_services(self)
def get_services_in_use(self)
Returns this bundle's ServiceReference list for all services it is using or an empty list. A bundle is considered to be using a service if its use count for that service is greater than zero. The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled
5.518563
6.10468
0.903989
# type: () -> str # Get the version value version = getattr(self.__module, "__version__", None) if version: return version # Convert the __version_info__ entry info = getattr(self.__module, "__version_info__", None) if info: return ".".join(str(part) for part in __version_info__) # No version return "0.0.0"
def get_version(self)
Retrieves the bundle version, using the ``__version__`` or ``__version_info__`` attributes of its module. :return: The bundle version, "0.0.0" by default
3.804128
3.940907
0.965292
if self.__framework._state not in (Bundle.STARTING, Bundle.ACTIVE): # Framework is not running raise BundleException( "Framework must be started before its bundles" ) with self._lock: if self._state in (Bundle.ACTIVE, Bundle.STARTING): # Already started bundle, do nothing return # Store the bundle current state previous_state = self._state # Starting... self._state = Bundle.STARTING self._fire_bundle_event(BundleEvent.STARTING) # Call the activator, if any starter = self.__get_activator_method("start") if starter is not None: try: # Call the start method starter(self.__context) except (FrameworkException, BundleException): # Restore previous state self._state = previous_state # Re-raise directly Pelix exceptions _logger.exception( "Pelix error raised by %s while starting", self.__name ) raise except Exception as ex: # Restore previous state self._state = previous_state # Raise the error _logger.exception( "Error raised by %s while starting", self.__name ) raise BundleException(ex) # Bundle is now active self._state = Bundle.ACTIVE self._fire_bundle_event(BundleEvent.STARTED)
def start(self)
Starts the bundle. Does nothing if the bundle is already starting or active. :raise BundleException: The framework is not yet started or the bundle activator failed.
3.500168
3.197721
1.094582
if self._state != Bundle.ACTIVE: # Invalid state return exception = None with self._lock: # Store the bundle current state previous_state = self._state # Stopping... self._state = Bundle.STOPPING self._fire_bundle_event(BundleEvent.STOPPING) # Call the activator, if any stopper = self.__get_activator_method("stop") if stopper is not None: try: # Call the start method stopper(self.__context) except (FrameworkException, BundleException) as ex: # Restore previous state self._state = previous_state # Re-raise directly Pelix exceptions _logger.exception( "Pelix error raised by %s while stopping", self.__name ) exception = ex except Exception as ex: _logger.exception( "Error raised by %s while stopping", self.__name ) # Store the exception (raised after service clean up) exception = BundleException(ex) # Hide remaining services self.__framework._hide_bundle_services(self) # Intermediate bundle event : activator should have cleaned up # everything, but some element could stay (iPOPO components, ...) self._fire_bundle_event(BundleEvent.STOPPING_PRECLEAN) # Remove remaining services (the hard way) self.__unregister_services() # Cleanup service usages self.__framework._unget_used_services(self) # Bundle is now stopped and all its services have been unregistered self._state = Bundle.RESOLVED self._fire_bundle_event(BundleEvent.STOPPED) # Raise the exception, if any # pylint: disable=E0702 # Pylint seems to miss the "is not None" check below if exception is not None: raise exception
def stop(self)
Stops the bundle. Does nothing if the bundle is already stopped. :raise BundleException: The bundle activator failed.
5.254874
4.960503
1.059343
# Copy the services list, as it will be modified during the process with self.__registration_lock: registered_services = self.__registered_services.copy() for registration in registered_services: try: registration.unregister() except BundleException: # Ignore errors at this level pass if self.__registered_services: _logger.warning("Not all services have been unregistered...") with self.__registration_lock: # Clear the list, just to be clean self.__registered_services.clear()
def __unregister_services(self)
Unregisters all bundle services
4.351806
4.098744
1.061741
with self._lock: if self._state == Bundle.ACTIVE: self.stop() # Change the bundle state self._state = Bundle.UNINSTALLED # Call the framework self.__framework.uninstall_bundle(self)
def uninstall(self)
Uninstalls the bundle
5.581166
4.727951
1.180462
with self._lock: # Was it active ? restart = self._state == Bundle.ACTIVE # Send the update event self._fire_bundle_event(BundleEvent.UPDATE_BEGIN) try: # Stop the bundle self.stop() except: # Something wrong occurred, notify listeners self._fire_bundle_event(BundleEvent.UPDATE_FAILED) raise # Change the source file age module_stat = None module_file = getattr(self.__module, "__file__", None) if module_file is not None and os.path.isfile(module_file): try: module_stat = os.stat(module_file) # Change modification time to bypass weak time resolution # of the underlying file system os.utime( module_file, (module_stat.st_atime, module_stat.st_mtime + 1), ) except OSError: # Can't touch the file _logger.warning( "Failed to update the modification time of '%s'. " "The bundle update might not reflect the latest " "changes.", module_file, ) # Clean up the module constants (otherwise kept by reload) # Keep special members (__name__, __file__, ...) old_content = self.__module.__dict__.copy() for name in list(self.__module.__dict__): if not (name.startswith("__") and name.endswith("__")): del self.__module.__dict__[name] try: # Reload the module reload_module(self.__module) except (ImportError, SyntaxError) as ex: # Exception raised if the file is unreadable _logger.exception("Error updating %s: %s", self.__name, ex) # Reset module content self.__module.__dict__.clear() self.__module.__dict__.update(old_content) if module_stat is not None: try: # Reset times os.utime( module_file, (module_stat.st_atime, module_stat.st_mtime), ) except OSError: # Shouldn't occur, since we succeeded before the update _logger.debug( "Failed to reset the modification time of '%s'", module_file, ) if restart: try: # Re-start the bundle self.start() except: # Something wrong occurred, notify listeners self._fire_bundle_event(BundleEvent.UPDATE_FAILED) raise # Bundle update finished self._fire_bundle_event(BundleEvent.UPDATED)
def update(self)
Updates the bundle
3.231026
3.172185
1.018549
# type: (str, object) -> bool with self.__properties_lock: if name in self.__properties: # Already stored property return False self.__properties[name] = value return True
def add_property(self, name, value)
Adds a property to the framework **if it is not yet set**. If the property already exists (same name), then nothing is done. Properties can't be updated. :param name: The property name :param value: The value to set :return: True if the property was stored, else False
4.002217
5.438974
0.73584
# type: (Optional[str], Optional[str], bool) -> Optional[List[ServiceReference]] return self._registry.find_service_references( clazz, ldap_filter, only_one )
def find_service_references( self, clazz=None, ldap_filter=None, only_one=False )
Finds all services references matching the given filter. :param clazz: Class implemented by the service :param ldap_filter: Service filter :param only_one: Return the first matching service reference only :return: A list of found reference, or None :raise BundleException: An error occurred looking for service references
2.83659
4.918745
0.57669
# type: (int) -> Union[Bundle, Framework] if bundle_id == 0: # "System bundle" return self with self.__bundles_lock: if bundle_id not in self.__bundles: raise BundleException("Invalid bundle ID {0}".format(bundle_id)) return self.__bundles[bundle_id]
def get_bundle_by_id(self, bundle_id)
Retrieves the bundle with the given ID :param bundle_id: ID of an installed bundle :return: The requested bundle :raise BundleException: The ID is invalid
3.96429
4.694532
0.844448
# type: (str) -> Optional[Bundle] if bundle_name is None: # Nothing to do return None if bundle_name is self.get_symbolic_name(): # System bundle requested return self with self.__bundles_lock: for bundle in self.__bundles.values(): if bundle_name == bundle.get_symbolic_name(): # Found ! return bundle # Not found... return None
def get_bundle_by_name(self, bundle_name)
Retrieves the bundle with the given name :param bundle_name: Name of the bundle to look for :return: The requested bundle, None if not found
3.552991
4.1392
0.858376
# type: () -> List[Bundle] with self.__bundles_lock: return [ self.__bundles[bundle_id] for bundle_id in sorted(self.__bundles.keys()) ]
def get_bundles(self)
Returns the list of all installed bundles :return: the list of all installed bundles
3.601777
4.882513
0.737689
# type: (str) -> object with self.__properties_lock: return self.__properties.get(name, os.getenv(name))
def get_property(self, name)
Retrieves a framework or system property. As framework properties don't change while it's running, this method don't need to be protected. :param name: The property name
5.549615
8.901443
0.623451
# type: (Bundle, ServiceReference) -> Any if not isinstance(bundle, Bundle): raise TypeError("First argument must be a Bundle object") elif not isinstance(reference, ServiceReference): raise TypeError("Second argument must be a ServiceReference object") try: # Unregistering service, just give it return self.__unregistering_services[reference] except KeyError: return self._registry.get_service(bundle, reference)
def get_service(self, bundle, reference)
Retrieves the service corresponding to the given reference :param bundle: The bundle requiring the service :param reference: A service reference :return: The requested service :raise BundleException: The service could not be found :raise TypeError: The argument is not a ServiceReference object
3.69065
4.263797
0.865578
# type: (str, str) -> Bundle with self.__bundles_lock: # A bundle can't be installed twice for bundle in self.__bundles.values(): if bundle.get_symbolic_name() == name: _logger.debug("Already installed bundle: %s", name) return bundle # Load the module try: if path: # Use the given path in priority sys.path.insert(0, path) try: # The module has already been loaded module_ = sys.modules[name] except KeyError: # Load the module # __import__(name) -> package level # import_module -> module level module_ = importlib.import_module(name) except (ImportError, IOError) as ex: # Error importing the module raise BundleException( "Error installing bundle {0}: {1}".format(name, ex) ) finally: if path: # Clean up the path. The loaded module(s) might # have changed the path content, so do not use an # index sys.path.remove(path) # Add the module to sys.modules, just to be sure sys.modules[name] = module_ # Compute the bundle ID bundle_id = self.__next_bundle_id # Prepare the bundle object and its context bundle = Bundle(self, bundle_id, name, module_) # Store the bundle self.__bundles[bundle_id] = bundle # Update the bundle ID counter self.__next_bundle_id += 1 # Fire the bundle installed event event = BundleEvent(BundleEvent.INSTALLED, bundle) self._dispatcher.fire_bundle_event(event) return bundle
def install_bundle(self, name, path=None)
Installs the bundle with the given name *Note:* Before Pelix 0.5.0, this method returned the ID of the installed bundle, instead of the Bundle object. **WARNING:** The behavior of the loading process is subject to changes, as it does not allow to safely run multiple frameworks in the same Python interpreter, as they might share global module values. :param name: A bundle name :param path: Preferred path to load the module :return: The installed Bundle object :raise BundleException: Something happened
3.397734
3.31533
1.024856
# type: (str, bool, str) -> tuple if not path: raise ValueError("Empty path") elif not is_string(path): raise ValueError("Path must be a string") # Use an absolute path path = os.path.abspath(path) if not os.path.exists(path): raise ValueError("Nonexistent path: {0}".format(path)) # Create a simple visitor def visitor(fullname, is_package, module_path): # pylint: disable=W0613 return recursive or not is_package # Set up the prefix if needed if prefix is None: prefix = os.path.basename(path) bundles = set() # type: Set[Bundle] failed = set() # type: Set[str] with self.__bundles_lock: try: # Install the package first, resolved from the parent directory bundles.add(self.install_bundle(prefix, os.path.dirname(path))) # Visit the package visited, sub_failed = self.install_visiting( path, visitor, prefix ) # Update the sets bundles.update(visited) failed.update(sub_failed) except BundleException as ex: # Error loading the module _logger.warning("Error loading package %s: %s", prefix, ex) failed.add(prefix) return bundles, failed
def install_package(self, path, recursive=False, prefix=None)
Installs all the modules found in the given package :param path: Path of the package (folder) :param recursive: If True, install the sub-packages too :param prefix: (**internal**) Prefix for all found modules :return: A 2-tuple, with the list of installed bundles and the list of failed modules names :raise ValueError: Invalid path
3.85529
3.764667
1.024072