2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2013 INRIA
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
20 from nepi.util.timefuncs import tnow, tdiff, tdiffsec, stabsformat
21 from nepi.util.logger import Logger
22 from nepi.execution.attribute import Attribute, Flags, Types
23 from nepi.execution.trace import TraceAttr
35 """ Action that a user can order to a Resource Manager
43 """ State of a Resource Manager
56 ResourceState2str = dict({
57 ResourceState.NEW : "NEW",
58 ResourceState.DISCOVERED : "DISCOVERED",
59 ResourceState.RESERVED : "RESERVED",
60 ResourceState.PROVISIONED : "PROVISIONED",
61 ResourceState.READY : "READY",
62 ResourceState.STARTED : "STARTED",
63 ResourceState.STOPPED : "STOPPED",
64 ResourceState.FAILED : "FAILED",
65 ResourceState.RELEASED : "RELEASED",
69 """ Initializes template information (i.e. attributes and traces)
70 on classes derived from the ResourceManager class.
72 It is used as a decorator in the class declaration as follows:
75 class MyResourceManager(ResourceManager):
84 def clsinit_copy(cls):
85 """ Initializes template information (i.e. attributes and traces)
86 on classes direved from the ResourceManager class.
87 It differs from the clsinit method in that it forces inheritance
88 of attributes and traces from the parent class.
90 It is used as a decorator in the class declaration as follows:
93 class MyResourceManager(ResourceManager):
98 clsinit_copy should be prefered to clsinit when creating new
99 ResourceManager child classes.
107 """ Decorator function for instance methods that should set the
108 RM state to FAILED when an error is raised. The methods that must be
109 decorated are: discover, reserved, provision, deploy, start, stop.
112 def wrapped(self, *args, **kwargs):
114 return func(self, *args, **kwargs)
119 err = traceback.format_exc()
120 logger = Logger(self._rtype)
122 logger.error("SETTING guid %d to state FAILED" % self.guid)
128 class ResourceManager(Logger):
129 """ Base clase for all ResourceManagers.
131 A ResourceManger is specific to a resource type (e.g. Node,
132 Switch, Application, etc) on a specific platform (e.g. PlanetLab,
135 The ResourceManager instances are responsible for interacting with
136 and controlling concrete (physical or virtual) resources in the
137 experimental platforms.
145 _reschedule_delay = "0.5s"
148 def _register_attribute(cls, attr):
149 """ Resource subclasses will invoke this method to add a
154 cls._attributes[attr.name] = attr
157 def _remove_attribute(cls, name):
158 """ Resource subclasses will invoke this method to remove a
163 del cls._attributes[name]
166 def _register_trace(cls, trace):
167 """ Resource subclasses will invoke this method to add a
172 cls._traces[trace.name] = trace
175 def _remove_trace(cls, name):
176 """ Resource subclasses will invoke this method to remove a
181 del cls._traces[name]
184 def _register_attributes(cls):
185 """ Resource subclasses will invoke this method to register
188 This method should be overriden in the RMs that define
192 critical = Attribute("critical",
193 "Defines whether the resource is critical. "
194 "A failure on a critical resource will interrupt "
198 flags = Flags.Design)
199 hard_release = Attribute("hardRelease",
200 "Forces removal of all result files and directories associated "
201 "to the RM upon resource release. After release the RM will "
202 "be removed from the EC and the results will not longer be "
206 flags = Flags.Design)
208 cls._register_attribute(critical)
209 cls._register_attribute(hard_release)
212 def _register_traces(cls):
213 """ Resource subclasses will invoke this method to register
216 This method should be overriden in the RMs that define traces.
224 """ ResourceManager classes have different attributes and traces.
225 Attribute and traces are stored in 'class attribute' dictionaries.
226 When a new ResourceManager class is created, the _clsinit method is
227 called to create a new instance of those dictionaries and initialize
230 The _clsinit method is called by the clsinit decorator method.
234 # static template for resource attributes
235 cls._attributes = dict()
236 cls._register_attributes()
238 # static template for resource traces
240 cls._register_traces()
243 def _clsinit_copy(cls):
244 """ Same as _clsinit, except that after creating new instances of the
245 dictionaries it copies all the attributes and traces from the parent
248 The _clsinit_copy method is called by the clsinit_copy decorator method.
251 # static template for resource attributes
252 cls._attributes = copy.deepcopy(cls._attributes)
253 cls._register_attributes()
255 # static template for resource traces
256 cls._traces = copy.deepcopy(cls._traces)
257 cls._register_traces()
261 """ Returns the type of the Resource Manager
267 def get_attributes(cls):
268 """ Returns a copy of the attributes
271 return copy.deepcopy(cls._attributes.values())
274 def get_attribute(cls, name):
275 """ Returns a copy of the attribute with name 'name'
278 return copy.deepcopy(cls._attributes[name])
282 """ Returns a copy of the traces
285 return copy.deepcopy(cls._traces.values())
289 """ Returns the description of the type of Resource
295 def get_platform(cls):
296 """ Returns the identified of the platform (i.e. testbed type)
303 def get_global(cls, name):
304 """ Returns the value of a global attribute
305 Global attribute meaning an attribute for
306 all the resources from a rtype
308 :param name: Name of the attribute
312 global_attr = cls._attributes[name]
313 return global_attr.value
316 def set_global(cls, name, value):
317 """ Set value for a global attribute
319 :param name: Name of the attribute
321 :param name: Value of the attribute
324 global_attr = cls._attributes[name]
325 global_attr.value = value
328 def __init__(self, ec, guid):
329 super(ResourceManager, self).__init__(self.get_rtype())
332 self._ec = weakref.ref(ec)
333 self._connections = set()
334 self._conditions = dict()
336 # the resource instance gets a copy of all attributes
337 self._attrs = copy.deepcopy(self._attributes)
339 # the resource instance gets a copy of all traces
340 self._trcs = copy.deepcopy(self._traces)
342 # Each resource is placed on a deployment group by the EC
344 self.deployment_group = None
346 self._start_time = None
347 self._stop_time = None
348 self._discover_time = None
349 self._reserved_time = None
350 self._provision_time = None
351 self._ready_time = None
352 self._release_time = None
353 self._failed_time = None
355 self._state = ResourceState.NEW
357 # instance lock to synchronize exclusive state change methods (such
358 # as deploy and release methods), in order to prevent them from being
359 # executed at the same time and corrupt internal resource state
360 self._release_lock = threading.Lock()
364 """ Returns the global unique identifier of the RM """
369 """ Returns the Experiment Controller of the RM """
373 def connections(self):
374 """ Returns the set of guids of connected RMs """
375 return self._connections
378 def conditions(self):
379 """ Returns the conditions to which the RM is subjected to.
381 This method returns a dictionary of conditions lists indexed by
385 return self._conditions
388 def start_time(self):
389 """ Returns the start time of the RM as a timestamp """
390 return self._start_time
394 """ Returns the stop time of the RM as a timestamp """
395 return self._stop_time
398 def discover_time(self):
399 """ Returns the discover time of the RM as a timestamp """
400 return self._discover_time
403 def reserved_time(self):
404 """ Returns the resreved time of the RM as a timestamp """
405 return self._reserved_time
408 def provision_time(self):
409 """ Returns the provision time of the RM as a timestamp """
410 return self._provision_time
413 def ready_time(self):
414 """ Returns the deployment time of the RM as a timestamp """
415 return self._ready_time
418 def release_time(self):
419 """ Returns the release time of the RM as a timestamp """
420 return self._release_time
423 def failed_time(self):
424 """ Returns the time failure occured for the RM as a timestamp """
425 return self._failed_time
429 """ Get the current state of the RM """
433 def reschedule_delay(self):
434 """ Returns default reschedule delay """
435 return self._reschedule_delay
437 def log_message(self, msg):
438 """ Returns the log message formatted with added information.
440 :param msg: text message
445 return " %s guid %d - %s " % (self._rtype, self.guid, msg)
447 def register_connection(self, guid):
448 """ Registers a connection to the RM identified by guid
450 This method should not be overriden. Specific functionality
451 should be added in the do_connect method.
453 :param guid: Global unique identified of the RM to connect to
457 if self.valid_connection(guid):
458 self.do_connect(guid)
459 self._connections.add(guid)
461 def unregister_connection(self, guid):
462 """ Removes a registered connection to the RM identified by guid
464 This method should not be overriden. Specific functionality
465 should be added in the do_disconnect method.
467 :param guid: Global unique identified of the RM to connect to
471 if guid in self._connections:
472 self.do_disconnect(guid)
473 self._connections.remove(guid)
477 """ Performs resource discovery.
479 This method is responsible for selecting an individual resource
480 matching user requirements.
482 This method should not be overriden directly. Specific functionality
483 should be added in the do_discover method.
486 with self._release_lock:
487 if self._state != ResourceState.RELEASED:
492 """ Performs resource reserve.
494 This method is responsible for reserving an individual resource
495 matching user requirements.
497 This method should not be overriden directly. Specific functionality
498 should be added in the do_reserved method.
501 with self._release_lock:
502 if self._state != ResourceState.RELEASED:
507 """ Performs resource provisioning.
509 This method is responsible for provisioning one resource.
510 After this method has been successfully invoked, the resource
511 should be accessible/controllable by the RM.
513 This method should not be overriden directly. Specific functionality
514 should be added in the do_provision method.
517 with self._release_lock:
518 if self._state != ResourceState.RELEASED:
523 """ Starts the RM (e.g. launch remote process).
525 There is no standard start behavior. Some RMs will not need to perform
526 any actions upon start.
528 This method should not be overriden directly. Specific functionality
529 should be added in the do_start method.
533 if not self.state in [ResourceState.READY, ResourceState.STOPPED]:
534 self.error("Wrong state %s for start" % self.state)
537 with self._release_lock:
538 if self._state != ResourceState.RELEASED:
543 """ Interrupts the RM, stopping any tasks the RM was performing.
545 There is no standard stop behavior. Some RMs will not need to perform
546 any actions upon stop.
548 This method should not be overriden directly. Specific functionality
549 should be added in the do_stop method.
552 if not self.state in [ResourceState.STARTED]:
553 self.error("Wrong state %s for stop" % self.state)
556 with self._release_lock:
561 """ Execute all steps required for the RM to reach the state READY.
563 This method is responsible for deploying the resource (and invoking
564 the discover and provision methods).
566 This method should not be overriden directly. Specific functionality
567 should be added in the do_deploy method.
570 if self.state > ResourceState.READY:
571 self.error("Wrong state %s for deploy" % self.state)
574 with self._release_lock:
575 if self._state != ResourceState.RELEASED:
579 """ Perform actions to free resources used by the RM.
581 This method is responsible for releasing resources that were
582 used during the experiment by the RM.
584 This method should not be overriden directly. Specific functionality
585 should be added in the do_release method.
588 with self._release_lock:
595 err = traceback.format_exc()
596 msg = " %s guid %d ----- FAILED TO RELEASE ----- \n %s " % (
597 self._rtype, self.guid, err)
598 logger = Logger(self._rtype)
602 """ Sets the RM to state FAILED.
604 This method should not be overriden directly. Specific functionality
605 should be added in the do_fail method.
608 with self._release_lock:
609 if self._state != ResourceState.RELEASED:
612 def set(self, name, value):
613 """ Set the value of the attribute
615 :param name: Name of the attribute
617 :param name: Value of the attribute
620 attr = self._attrs[name]
625 """ Returns the value of the attribute
627 :param name: Name of the attribute
631 attr = self._attrs[name]
634 A.Q. Commenting due to performance impact
635 if attr.has_flag(Flags.Global):
636 self.warning( "Attribute %s is global. Use get_global instead." % name)
641 def has_changed(self, name):
642 """ Returns the True is the value of the attribute
643 has been modified by the user.
645 :param name: Name of the attribute
649 attr = self._attrs[name]
650 return attr.has_changed
652 def has_flag(self, name, flag):
653 """ Returns true if the attribute has the flag 'flag'
655 :param flag: Flag to be checked
658 attr = self._attrs[name]
659 return attr.has_flag(flag)
661 def has_attribute(self, name):
662 """ Returns true if the RM has an attribute with name
664 :param name: name of the attribute
667 return name in self._attrs
669 def enable_trace(self, name):
670 """ Explicitly enable trace generation
672 :param name: Name of the trace
675 trace = self._trcs[name]
678 def trace_enabled(self, name):
679 """Returns True if trace is enables
681 :param name: Name of the trace
684 trace = self._trcs[name]
687 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
688 """ Get information on collected trace
690 :param name: Name of the trace
693 :param attr: Can be one of:
694 - TraceAttr.ALL (complete trace content),
695 - TraceAttr.STREAM (block in bytes to read starting at offset),
696 - TraceAttr.PATH (full path to the trace file),
697 - TraceAttr.SIZE (size of trace file).
700 :param block: Number of bytes to retrieve from trace, when attr is TraceAttr.STREAM
703 :param offset: Number of 'blocks' to skip, when attr is TraceAttr.STREAM
710 def register_condition(self, action, group, state, time = None):
711 """ Registers a condition on the resource manager to allow execution
712 of 'action' only after 'time' has elapsed from the moment all resources
713 in 'group' reached state 'state'
715 :param action: Action to restrict to condition (either 'START' or 'STOP')
717 :param group: Group of RMs to wait for (list of guids)
718 :type group: int or list of int
719 :param state: State to wait for on all RM in group. (either 'STARTED', 'STOPPED' or 'READY')
721 :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
726 if not action in self.conditions:
727 self._conditions[action] = list()
729 conditions = self.conditions.get(action)
731 # For each condition to register a tuple of (group, state, time) is
732 # added to the 'action' list
733 if not isinstance(group, list):
736 conditions.append((group, state, time))
738 def unregister_condition(self, group, action = None):
739 """ Removed conditions for a certain group of guids
741 :param action: Action to restrict to condition (either 'START', 'STOP' or 'READY')
744 :param group: Group of RMs to wait for (list of guids)
745 :type group: int or list of int
748 # For each condition a tuple of (group, state, time) is
749 # added to the 'action' list
750 if not isinstance(group, list):
753 for act, conditions in self.conditions.iteritems():
754 if action and act != action:
757 for condition in list(conditions):
758 (grp, state, time) = condition
760 # If there is an intersection between grp and group,
761 # then remove intersected elements
762 intsec = set(group).intersection(set(grp))
764 idx = conditions.index(condition)
766 newgrp.difference_update(intsec)
767 conditions[idx] = (newgrp, state, time)
769 def get_connected(self, rtype = None):
770 """ Returns the list of RM with the type 'rtype'
772 :param rtype: Type of the RM we look for
774 :return: list of guid
777 rclass = ResourceFactory.get_resource_type(rtype)
778 for guid in self.connections:
779 rm = self.ec.get_resource(guid)
780 if not rtype or isinstance(rm, rclass):
784 def is_rm_instance(self, rtype):
785 """ Returns True if the RM is instance of 'rtype'
787 :param rtype: Type of the RM we look for
791 rclass = ResourceFactory.get_resource_type(rtype)
792 if isinstance(self, rclass):
797 def _needs_reschedule(self, group, state, time):
798 """ Internal method that verify if 'time' has elapsed since
799 all elements in 'group' have reached state 'state'.
801 :param group: Group of RMs to wait for (list of guids)
802 :type group: int or list of int
803 :param state: State to wait for on all RM in group. (either 'STARTED', 'STOPPED' or 'READY')
805 :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
808 .. note : time should be written like "2s" or "3m" with s for seconds, m for minutes, h for hours, ...
809 If for example, you need to wait 2min 30sec, time could be "150s" or "2.5m".
810 For the moment, 2m30s is not a correct syntax.
814 delay = self.reschedule_delay
816 # check state and time elapsed on all RMs
818 rm = self.ec.get_resource(guid)
820 # If one of the RMs this resource needs to wait for has FAILED
821 # and is critical we raise an exception
822 if rm.state == ResourceState.FAILED:
823 if not rm.get('critical'):
825 msg = "Resource can not wait for FAILED RM %d. Setting Resource to FAILED"
826 raise RuntimeError, msg
828 # If the RM state is lower than the requested state we must
829 # reschedule (e.g. if RM is READY but we required STARTED).
834 # If there is a time restriction, we must verify the
835 # restriction is satisfied
837 if state == ResourceState.DISCOVERED:
839 elif state == ResourceState.RESERVED:
841 elif state == ResourceState.PROVISIONED:
842 t = rm.provision_time
843 elif state == ResourceState.READY:
845 elif state == ResourceState.STARTED:
847 elif state == ResourceState.STOPPED:
849 elif state == ResourceState.RELEASED:
854 # time already elapsed since RM changed state
855 waited = "%fs" % tdiffsec(tnow(), t)
858 wait = tdiffsec(stabsformat(time), stabsformat(waited))
865 return reschedule, delay
867 def set_with_conditions(self, name, value, group, state, time):
868 """ Set value 'value' on attribute with name 'name' when 'time'
869 has elapsed since all elements in 'group' have reached state
872 :param name: Name of the attribute to set
874 :param name: Value of the attribute to set
876 :param group: Group of RMs to wait for (list of guids)
877 :type group: int or list of int
878 :param state: State to wait for on all RM in group. (either 'STARTED', 'STOPPED' or 'READY')
880 :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
885 delay = self.reschedule_delay
887 ## evaluate if set conditions are met
889 # only can set with conditions after the RM is started
890 if self.state != ResourceState.STARTED:
893 reschedule, delay = self._needs_reschedule(group, state, time)
896 callback = functools.partial(self.set_with_conditions,
897 name, value, group, state, time)
898 self.ec.schedule(delay, callback)
900 self.set(name, value)
902 def start_with_conditions(self):
903 """ Starts RM when all the conditions in self.conditions for
904 action 'START' are satisfied.
907 #import pdb;pdb.set_trace()
910 delay = self.reschedule_delay
913 ## evaluate if conditions to start are met
917 # Can only start when RM is either STOPPED or READY
918 if self.state not in [ResourceState.STOPPED, ResourceState.READY]:
920 self.debug("---- RESCHEDULING START ---- state %s " % self.state )
922 start_conditions = self.conditions.get(ResourceAction.START, [])
924 self.debug("---- START CONDITIONS ---- %s" % start_conditions)
926 # Verify all start conditions are met
927 for (group, state, time) in start_conditions:
928 # Uncomment for debug
931 # rm = self.ec.get_resource(guid)
932 # unmet.append((guid, rm._state))
934 #self.debug("---- WAITED STATES ---- %s" % unmet )
936 reschedule, delay = self._needs_reschedule(group, state, time)
941 self.ec.schedule(delay, self.start_with_conditions)
943 self.debug("----- STARTING ---- ")
946 def stop_with_conditions(self):
947 """ Stops RM when all the conditions in self.conditions for
948 action 'STOP' are satisfied.
952 delay = self.reschedule_delay
954 ## evaluate if conditions to stop are met
958 # only can stop when RM is STARTED
959 if self.state != ResourceState.STARTED:
961 self.debug("---- RESCHEDULING STOP ---- state %s " % self.state )
963 self.debug(" ---- STOP CONDITIONS ---- %s" %
964 self.conditions.get(ResourceAction.STOP))
966 stop_conditions = self.conditions.get(ResourceAction.STOP, [])
967 for (group, state, time) in stop_conditions:
968 reschedule, delay = self._needs_reschedule(group, state, time)
973 callback = functools.partial(self.stop_with_conditions)
974 self.ec.schedule(delay, callback)
976 self.debug(" ----- STOPPING ---- ")
979 def deploy_with_conditions(self):
980 """ Deploy RM when all the conditions in self.conditions for
981 action 'READY' are satisfied.
985 delay = self.reschedule_delay
987 ## evaluate if conditions to deploy are met
991 # only can deploy when RM is either NEW, DISCOVERED or PROVISIONED
992 if self.state not in [ResourceState.NEW, ResourceState.DISCOVERED,
993 ResourceState.RESERVED, ResourceState.PROVISIONED]:
994 #### XXX: A.Q. IT SHOULD FAIL IF DEPLOY IS CALLED IN OTHER STATES!
996 self.debug("---- RESCHEDULING DEPLOY ---- state %s " % self.state )
998 deploy_conditions = self.conditions.get(ResourceAction.DEPLOY, [])
1000 self.debug("---- DEPLOY CONDITIONS ---- %s" % deploy_conditions)
1002 # Verify all start conditions are met
1003 for (group, state, time) in deploy_conditions:
1004 # Uncomment for debug
1007 # rm = self.ec.get_resource(guid)
1008 # unmet.append((guid, rm._state))
1010 #self.debug("---- WAITED STATES ---- %s" % unmet )
1012 reschedule, delay = self._needs_reschedule(group, state, time)
1017 self.ec.schedule(delay, self.deploy_with_conditions)
1019 self.debug("----- DEPLOYING ---- ")
1022 def do_connect(self, guid):
1023 """ Performs actions that need to be taken upon associating RMs.
1024 This method should be redefined when necessary in child classes.
1028 def do_disconnect(self, guid):
1029 """ Performs actions that need to be taken upon disassociating RMs.
1030 This method should be redefined when necessary in child classes.
1034 def valid_connection(self, guid):
1035 """Checks whether a connection with the other RM
1037 This method need to be redefined by each new Resource Manager.
1039 :param guid: Guid of the current Resource Manager
1047 def do_discover(self):
1048 self.set_discovered()
1050 def do_reserve(self):
1053 def do_provision(self):
1054 self.set_provisioned()
1062 def do_deploy(self):
1065 def do_release(self):
1070 self.ec.inform_failure(self.guid)
1072 def set_started(self, time = None):
1073 """ Mark ResourceManager as STARTED """
1074 self.set_state(ResourceState.STARTED, "_start_time", time)
1075 self.debug("----- STARTED ---- ")
1077 def set_stopped(self, time = None):
1078 """ Mark ResourceManager as STOPPED """
1079 self.set_state(ResourceState.STOPPED, "_stop_time", time)
1080 self.debug("----- STOPPED ---- ")
1082 def set_ready(self, time = None):
1083 """ Mark ResourceManager as READY """
1084 self.set_state(ResourceState.READY, "_ready_time", time)
1085 self.debug("----- READY ---- ")
1087 def set_released(self, time = None):
1088 """ Mark ResourceManager as REALEASED """
1089 self.set_state(ResourceState.RELEASED, "_release_time", time)
1091 msg = " %s guid %d ----- RELEASED ----- " % (self._rtype, self.guid)
1092 logger = Logger(self._rtype)
1095 def set_failed(self, time = None):
1096 """ Mark ResourceManager as FAILED """
1097 self.set_state(ResourceState.FAILED, "_failed_time", time)
1099 msg = " %s guid %d ----- FAILED ----- " % (self._rtype, self.guid)
1100 logger = Logger(self._rtype)
1103 def set_discovered(self, time = None):
1104 """ Mark ResourceManager as DISCOVERED """
1105 self.set_state(ResourceState.DISCOVERED, "_discover_time", time)
1106 self.debug("----- DISCOVERED ---- ")
1108 def set_reserved(self, time = None):
1109 """ Mark ResourceManager as RESERVED """
1110 self.set_state(ResourceState.RESERVED, "_reserved_time", time)
1111 self.debug("----- RESERVED ---- ")
1113 def set_provisioned(self, time = None):
1114 """ Mark ResourceManager as PROVISIONED """
1115 self.set_state(ResourceState.PROVISIONED, "_provision_time", time)
1116 self.debug("----- PROVISIONED ---- ")
1118 def set_state(self, state, state_time_attr, time = None):
1119 """ Set the state of the RM while keeping a trace of the time """
1121 # Ensure that RM state will not change after released
1122 if self._state == ResourceState.RELEASED:
1125 time = time or tnow()
1126 self.set_state_time(state, state_time_attr, time)
1128 def set_state_time(self, state, state_time_attr, time):
1129 """ Set the time for the RM state change """
1130 setattr(self, state_time_attr, time)
1133 class ResourceFactory(object):
1134 _resource_types = dict()
1137 def resource_types(cls):
1138 """Return the type of the Class"""
1139 return cls._resource_types
1142 def get_resource_type(cls, rtype):
1143 """Return the type of the Class"""
1144 return cls._resource_types.get(rtype)
1147 def register_type(cls, rclass):
1148 """Register a new Ressource Manager"""
1149 cls._resource_types[rclass.get_rtype()] = rclass
1152 def create(cls, rtype, ec, guid):
1153 """Create a new instance of a Ressource Manager"""
1154 rclass = cls._resource_types[rtype]
1155 return rclass(ec, guid)
1157 def populate_factory():
1158 """Find and rgister all available RMs
1160 # Once the factory is populated, don't repopulate
1161 if not ResourceFactory.resource_types():
1162 for rclass in find_types():
1163 ResourceFactory.register_type(rclass)
1166 """Look into the different folders to find all the
1167 availables Resources Managers
1169 search_path = os.environ.get("NEPI_SEARCH_PATH", "")
1170 search_path = set(search_path.split(" "))
1173 import nepi.resources
1174 path = os.path.dirname(nepi.resources.__file__)
1175 search_path.add(path)
1179 for importer, modname, ispkg in pkgutil.walk_packages(search_path,
1180 prefix = "nepi.resources."):
1182 loader = importer.find_module(modname)
1185 # Notice: Repeated calls to load_module will act as a reload of the module
1186 if modname in sys.modules:
1187 module = sys.modules.get(modname)
1189 module = loader.load_module(modname)
1191 for attrname in dir(module):
1192 if attrname.startswith("_"):
1195 attr = getattr(module, attrname)
1197 if attr == ResourceManager:
1200 if not inspect.isclass(attr):
1203 if issubclass(attr, ResourceManager):
1206 if not modname in sys.modules:
1207 sys.modules[modname] = module
1212 err = traceback.format_exc()
1213 logger = logging.getLogger("Resource.find_types()")
1214 logger.error("Error while loading Resource Managers %s" % err)