Fixing tickets http://newyans.pl.sophia.inria.fr/trac/ticket/37 and http://newyans...
[nepi.git] / src / nepi / execution / resource.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 INRIA
4 #
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.
9 #
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.
14 #
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/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
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
24
25 import copy
26 import functools
27 import logging
28 import os
29 import pkgutil
30 import sys
31 import threading
32 import weakref
33
34 reschedule_delay = "1s"
35
36 class ResourceAction:
37     """ Action that a user can order to a Resource Manager
38    
39     """
40     DEPLOY = 0
41     START = 1
42     STOP = 2
43
44 class ResourceState:
45     """ State of a Resource Manager
46    
47     """
48     NEW = 0
49     DISCOVERED = 1
50     PROVISIONED = 2
51     READY = 3
52     STARTED = 4
53     STOPPED = 5
54     FINISHED = 6
55     FAILED = 7
56     RELEASED = 8
57
58 ResourceState2str = dict({
59     ResourceState.NEW : "NEW",
60     ResourceState.DISCOVERED : "DISCOVERED",
61     ResourceState.PROVISIONED : "PROVISIONED",
62     ResourceState.READY : "READY",
63     ResourceState.STARTED : "STARTED",
64     ResourceState.STOPPED : "STOPPED",
65     ResourceState.FINISHED : "FINISHED",
66     ResourceState.FAILED : "FAILED",
67     ResourceState.RELEASED : "RELEASED",
68     })
69
70 def clsinit(cls):
71     """ Initializes template information (i.e. attributes and traces)
72     on classes derived from the ResourceManager class.
73
74     It is used as a decorator in the class declaration as follows:
75
76         @clsinit
77         class MyResourceManager(ResourceManager):
78         
79             ...
80
81      """
82
83     cls._clsinit()
84     return cls
85
86 def clsinit_copy(cls):
87     """ Initializes template information (i.e. attributes and traces)
88     on classes direved from the ResourceManager class.
89     It differs from the clsinit method in that it forces inheritance
90     of attributes and traces from the parent class.
91
92     It is used as a decorator in the class declaration as follows:
93
94         @clsinit
95         class MyResourceManager(ResourceManager):
96         
97             ...
98
99
100     clsinit_copy should be prefered to clsinit when creating new
101     ResourceManager child classes.
102
103     """
104     
105     cls._clsinit_copy()
106     return cls
107
108 def failtrap(func):
109     """ Decorator function for instance methods that should set the 
110     RM state to FAILED when an error is raised. The methods that must be
111     decorated are: discover, provision, deploy, start, stop and finish.
112
113     """
114     def wrapped(self, *args, **kwargs):
115         try:
116             return func(self, *args, **kwargs)
117         except:
118             import traceback
119             err = traceback.format_exc()
120             self.error(err)
121             self.debug("SETTING guid %d to state FAILED" % self.guid)
122             self.fail()
123             raise
124     
125     return wrapped
126
127 @clsinit
128 class ResourceManager(Logger):
129     """ Base clase for all ResourceManagers. 
130     
131     A ResourceManger is specific to a resource type (e.g. Node, 
132     Switch, Application, etc) on a specific backend (e.g. PlanetLab, 
133     OMF, etc).
134
135     The ResourceManager instances are responsible for interacting with
136     and controlling concrete (physical or virtual) resources in the 
137     experimental backends.
138     
139     """
140     _rtype = "Resource"
141     _attributes = None
142     _traces = None
143     _help = None
144     _backend = None
145
146     @classmethod
147     def _register_attribute(cls, attr):
148         """ Resource subclasses will invoke this method to add a 
149         resource attribute
150
151         """
152         
153         cls._attributes[attr.name] = attr
154
155     @classmethod
156     def _remove_attribute(cls, name):
157         """ Resource subclasses will invoke this method to remove a 
158         resource attribute
159
160         """
161         
162         del cls._attributes[name]
163
164     @classmethod
165     def _register_trace(cls, trace):
166         """ Resource subclasses will invoke this method to add a 
167         resource trace
168
169         """
170         
171         cls._traces[trace.name] = trace
172
173     @classmethod
174     def _remove_trace(cls, name):
175         """ Resource subclasses will invoke this method to remove a 
176         resource trace
177
178         """
179         
180         del cls._traces[name]
181
182     @classmethod
183     def _register_attributes(cls):
184         """ Resource subclasses will invoke this method to register
185         resource attributes.
186
187         This method should be overriden in the RMs that define
188         attributes.
189
190         """
191         
192         critical = Attribute("critical", 
193                 "Defines whether the resource is critical. "
194                 "A failure on a critical resource will interrupt "
195                 "the experiment. ",
196                 type = Types.Bool,
197                 default = True,
198                 flags = Flags.ExecReadOnly)
199
200         cls._register_attribute(critical)
201         
202     @classmethod
203     def _register_traces(cls):
204         """ Resource subclasses will invoke this method to register
205         resource traces
206
207         This method should be overriden in the RMs that define traces.
208         
209         """
210         
211         pass
212
213     @classmethod
214     def _clsinit(cls):
215         """ ResourceManager classes have different attributes and traces.
216         Attribute and traces are stored in 'class attribute' dictionaries.
217         When a new ResourceManager class is created, the _clsinit method is 
218         called to create a new instance of those dictionaries and initialize 
219         them.
220         
221         The _clsinit method is called by the clsinit decorator method.
222         
223         """
224         
225         # static template for resource attributes
226         cls._attributes = dict()
227         cls._register_attributes()
228
229         # static template for resource traces
230         cls._traces = dict()
231         cls._register_traces()
232
233     @classmethod
234     def _clsinit_copy(cls):
235         """ Same as _clsinit, except that after creating new instances of the
236         dictionaries it copies all the attributes and traces from the parent 
237         class.
238         
239         The _clsinit_copy method is called by the clsinit_copy decorator method.
240         
241         """
242         # static template for resource attributes
243         cls._attributes = copy.deepcopy(cls._attributes)
244         cls._register_attributes()
245
246         # static template for resource traces
247         cls._traces = copy.deepcopy(cls._traces)
248         cls._register_traces()
249
250     @classmethod
251     def rtype(cls):
252         """ Returns the type of the Resource Manager
253
254         """
255         return cls._rtype
256
257     @classmethod
258     def get_attributes(cls):
259         """ Returns a copy of the attributes
260
261         """
262         return copy.deepcopy(cls._attributes.values())
263
264     @classmethod
265     def get_traces(cls):
266         """ Returns a copy of the traces
267
268         """
269         return copy.deepcopy(cls._traces.values())
270
271     @classmethod
272     def get_help(cls):
273         """ Returns the description of the type of Resource
274
275         """
276         return cls._help
277
278     @classmethod
279     def get_backend(cls):
280         """ Returns the identified of the backend (i.e. testbed, environment)
281         for the Resource
282
283         """
284         return cls._backend
285
286     def __init__(self, ec, guid):
287         super(ResourceManager, self).__init__(self.rtype())
288         
289         self._guid = guid
290         self._ec = weakref.ref(ec)
291         self._connections = set()
292         self._conditions = dict() 
293
294         # the resource instance gets a copy of all attributes
295         self._attrs = copy.deepcopy(self._attributes)
296
297         # the resource instance gets a copy of all traces
298         self._trcs = copy.deepcopy(self._traces)
299
300         # Each resource is placed on a deployment group by the EC
301         # during deployment
302         self.deployment_group = None
303
304         self._start_time = None
305         self._stop_time = None
306         self._discover_time = None
307         self._provision_time = None
308         self._ready_time = None
309         self._release_time = None
310         self._finish_time = None
311         self._failed_time = None
312
313         self._state = ResourceState.NEW
314
315         # instance lock to synchronize exclusive state change methods (such
316         # as deploy and release methods), in order to prevent them from being 
317         # executed at the same time
318         self._release_lock = threading.Lock()
319
320     @property
321     def guid(self):
322         """ Returns the global unique identifier of the RM """
323         return self._guid
324
325     @property
326     def ec(self):
327         """ Returns the Experiment Controller of the RM """
328         return self._ec()
329
330     @property
331     def connections(self):
332         """ Returns the set of guids of connected RMs """
333         return self._connections
334
335     @property
336     def conditions(self):
337         """ Returns the conditions to which the RM is subjected to.
338         
339         This method returns a dictionary of conditions lists indexed by
340         a ResourceAction.
341         
342         """
343         return self._conditions
344
345     @property
346     def start_time(self):
347         """ Returns the start time of the RM as a timestamp """
348         return self._start_time
349
350     @property
351     def stop_time(self):
352         """ Returns the stop time of the RM as a timestamp """
353         return self._stop_time
354
355     @property
356     def discover_time(self):
357         """ Returns the discover time of the RM as a timestamp """
358         return self._discover_time
359
360     @property
361     def provision_time(self):
362         """ Returns the provision time of the RM as a timestamp """
363         return self._provision_time
364
365     @property
366     def ready_time(self):
367         """ Returns the deployment time of the RM as a timestamp """
368         return self._ready_time
369
370     @property
371     def release_time(self):
372         """ Returns the release time of the RM as a timestamp """
373         return self._release_time
374
375     @property
376     def finish_time(self):
377         """ Returns the finalization time of the RM as a timestamp """
378         return self._finish_time
379
380     @property
381     def failed_time(self):
382         """ Returns the time failure occured for the RM as a timestamp """
383         return self._failed_time
384
385     @property
386     def state(self):
387         """ Get the current state of the RM """
388         return self._state
389
390     def log_message(self, msg):
391         """ Returns the log message formatted with added information.
392
393         :param msg: text message
394         :type msg: str
395         :rtype: str
396
397         """
398         return " %s guid: %d - %s " % (self._rtype, self.guid, msg)
399
400     def register_connection(self, guid):
401         """ Registers a connection to the RM identified by guid
402
403         This method should not be overriden. Specific functionality
404         should be added in the do_connect method.
405
406         :param guid: Global unique identified of the RM to connect to
407         :type guid: int
408
409         """
410         if self.valid_connection(guid):
411             self.do_connect(guid)
412             self._connections.add(guid)
413
414     def unregister_connection(self, guid):
415         """ Removes a registered connection to the RM identified by guid
416         
417         This method should not be overriden. Specific functionality
418         should be added in the do_disconnect method.
419
420         :param guid: Global unique identified of the RM to connect to
421         :type guid: int
422
423         """
424         if guid in self._connections:
425             self.do_disconnect(guid)
426             self._connections.remove(guid)
427
428     @failtrap
429     def discover(self):
430         """ Performs resource discovery.
431         
432         This  method is responsible for selecting an individual resource
433         matching user requirements.
434
435         This method should not be overriden directly. Specific functionality
436         should be added in the do_discover method.
437
438         """
439         with self._release_lock:
440             if self._state != ResourceState.RELEASED:
441                 self.do_discover()
442
443     @failtrap
444     def provision(self):
445         """ Performs resource provisioning.
446
447         This  method is responsible for provisioning one resource.
448         After this method has been successfully invoked, the resource
449         should be accessible/controllable by the RM.
450
451         This method should not be overriden directly. Specific functionality
452         should be added in the do_provision method.
453
454         """
455         with self._release_lock:
456             if self._state != ResourceState.RELEASED:
457                 self.do_provision()
458
459     @failtrap
460     def start(self):
461         """ Starts the RM (e.g. launch remote process).
462     
463         There is no standard start behavior. Some RMs will not need to perform
464         any actions upon start.
465
466         This method should not be overriden directly. Specific functionality
467         should be added in the do_start method.
468
469         """
470         if not self.state in [ResourceState.READY, ResourceState.STOPPED]:
471             self.error("Wrong state %s for start" % self.state)
472             return
473
474         with self._release_lock:
475             if self._state != ResourceState.RELEASED:
476                 self.do_start()
477
478     @failtrap
479     def stop(self):
480         """ Interrupts the RM, stopping any tasks the RM was performing.
481      
482         There is no standard stop behavior. Some RMs will not need to perform
483         any actions upon stop.
484     
485         This method should not be overriden directly. Specific functionality
486         should be added in the do_stop method.
487       
488         """
489         if not self.state in [ResourceState.STARTED]:
490             self.error("Wrong state %s for stop" % self.state)
491             return
492         
493         with self._release_lock:
494             self.do_stop()
495
496     @failtrap
497     def deploy(self):
498         """ Execute all steps required for the RM to reach the state READY.
499
500         This method is responsible for deploying the resource (and invoking 
501         the discover and provision methods).
502  
503         This method should not be overriden directly. Specific functionality
504         should be added in the do_deploy method.
505        
506         """
507         if self.state > ResourceState.READY:
508             self.error("Wrong state %s for deploy" % self.state)
509             return
510
511         with self._release_lock:
512             if self._state != ResourceState.RELEASED:
513                 self.do_deploy()
514                 self.debug("----- READY ---- ")
515
516     def release(self):
517         """ Perform actions to free resources used by the RM.
518   
519         This  method is responsible for releasing resources that were
520         used during the experiment by the RM.
521
522         This method should not be overriden directly. Specific functionality
523         should be added in the do_release method.
524       
525         """
526         with self._release_lock:
527             try:
528                 self.do_release()
529             except:
530                 import traceback
531                 err = traceback.format_exc()
532                 self.error(err)
533
534             self.set_released()
535             self.debug("----- RELEASED ---- ")
536
537     @failtrap
538     def finish(self):
539         """ Sets the RM to state FINISHED. 
540      
541         The FINISHED state is different from STOPPED state in that it 
542         should not be directly invoked by the user.
543         STOPPED indicates that the user interrupted the RM, FINISHED means
544         that the RM concluded normally the actions it was supposed to perform.
545     
546         This method should not be overriden directly. Specific functionality
547         should be added in the do_finish method.
548         
549         """
550         with self._release_lock:
551             if self._state != ResourceState.RELEASED:
552                 self.do_finish()
553
554     def fail(self):
555         """ Sets the RM to state FAILED.
556
557         This method should not be overriden directly. Specific functionality
558         should be added in the do_fail method.
559
560         """
561         with self._release_lock:
562             if self._state != ResourceState.RELEASED:
563                 self.do_fail()
564
565     def set(self, name, value):
566         """ Set the value of the attribute
567
568         :param name: Name of the attribute
569         :type name: str
570         :param name: Value of the attribute
571         :type name: str
572         """
573         attr = self._attrs[name]
574         attr.value = value
575
576     def get(self, name):
577         """ Returns the value of the attribute
578
579         :param name: Name of the attribute
580         :type name: str
581         :rtype: str
582         """
583         attr = self._attrs[name]
584         return attr.value
585
586     def enable_trace(self, name):
587         """ Explicitly enable trace generation
588
589         :param name: Name of the trace
590         :type name: str
591         """
592         trace = self._trcs[name]
593         trace.enabled = True
594     
595     def trace_enabled(self, name):
596         """Returns True if trace is enables 
597
598         :param name: Name of the trace
599         :type name: str
600         """
601         trace = self._trcs[name]
602         return trace.enabled
603  
604     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
605         """ Get information on collected trace
606
607         :param name: Name of the trace
608         :type name: str
609
610         :param attr: Can be one of:
611                          - TraceAttr.ALL (complete trace content), 
612                          - TraceAttr.STREAM (block in bytes to read starting at offset), 
613                          - TraceAttr.PATH (full path to the trace file),
614                          - TraceAttr.SIZE (size of trace file). 
615         :type attr: str
616
617         :param block: Number of bytes to retrieve from trace, when attr is TraceAttr.STREAM 
618         :type name: int
619
620         :param offset: Number of 'blocks' to skip, when attr is TraceAttr.STREAM 
621         :type name: int
622
623         :rtype: str
624         """
625         pass
626
627     def register_condition(self, action, group, state, time = None):
628         """ Registers a condition on the resource manager to allow execution 
629         of 'action' only after 'time' has elapsed from the moment all resources 
630         in 'group' reached state 'state'
631
632         :param action: Action to restrict to condition (either 'START' or 'STOP')
633         :type action: str
634         :param group: Group of RMs to wait for (list of guids)
635         :type group: int or list of int
636         :param state: State to wait for on all RM in group. (either 'STARTED', 'STOPPED' or 'READY')
637         :type state: str
638         :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
639         :type time: str
640
641         """
642
643         if not action in self.conditions:
644             self._conditions[action] = list()
645         
646         conditions = self.conditions.get(action)
647
648         # For each condition to register a tuple of (group, state, time) is 
649         # added to the 'action' list
650         if not isinstance(group, list):
651             group = [group]
652
653         conditions.append((group, state, time))
654
655     def unregister_condition(self, group, action = None):
656         """ Removed conditions for a certain group of guids
657
658         :param action: Action to restrict to condition (either 'START', 'STOP' or 'READY')
659         :type action: str
660
661         :param group: Group of RMs to wait for (list of guids)
662         :type group: int or list of int
663
664         """
665         # For each condition a tuple of (group, state, time) is 
666         # added to the 'action' list
667         if not isinstance(group, list):
668             group = [group]
669
670         for act, conditions in self.conditions.iteritems():
671             if action and act != action:
672                 continue
673
674             for condition in list(conditions):
675                 (grp, state, time) = condition
676
677                 # If there is an intersection between grp and group,
678                 # then remove intersected elements
679                 intsec = set(group).intersection(set(grp))
680                 if intsec:
681                     idx = conditions.index(condition)
682                     newgrp = set(grp)
683                     newgrp.difference_update(intsec)
684                     conditions[idx] = (newgrp, state, time)
685                  
686     def get_connected(self, rtype = None):
687         """ Returns the list of RM with the type 'rtype'
688
689         :param rtype: Type of the RM we look for
690         :type rtype: str
691         :return: list of guid
692         """
693         connected = []
694         rclass = ResourceFactory.get_resource_type(rtype)
695         for guid in self.connections:
696             rm = self.ec.get_resource(guid)
697             if not rtype or isinstance(rm, rclass):
698                 connected.append(rm)
699         return connected
700
701     @failtrap
702     def _needs_reschedule(self, group, state, time):
703         """ Internal method that verify if 'time' has elapsed since 
704         all elements in 'group' have reached state 'state'.
705
706         :param group: Group of RMs to wait for (list of guids)
707         :type group: int or list of int
708         :param state: State to wait for on all RM in group. (either 'STARTED', 'STOPPED' or 'READY')
709         :type state: str
710         :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
711         :type time: str
712
713         .. note : time should be written like "2s" or "3m" with s for seconds, m for minutes, h for hours, ...
714         If for example, you need to wait 2min 30sec, time could be "150s" or "2.5m".
715         For the moment, 2m30s is not a correct syntax.
716
717         """
718         reschedule = False
719         delay = reschedule_delay 
720
721         # check state and time elapsed on all RMs
722         for guid in group:
723             rm = self.ec.get_resource(guid)
724             
725             # If one of the RMs this resource needs to wait for has FAILED
726             # we raise an exception
727             if rm.state == ResourceState.FAILED:
728                 msg = "Resource can not wait for FAILED RM %d. Setting Resource to FAILED"
729                 raise RuntimeError, msg
730
731             # If the RM state is lower than the requested state we must
732             # reschedule (e.g. if RM is READY but we required STARTED).
733             if rm.state < state:
734                 reschedule = True
735                 break
736
737             # If there is a time restriction, we must verify the
738             # restriction is satisfied 
739             if time:
740                 if state == ResourceState.DISCOVERED:
741                     t = rm.discover_time
742                 if state == ResourceState.PROVISIONED:
743                     t = rm.provision_time
744                 elif state == ResourceState.READY:
745                     t = rm.ready_time
746                 elif state == ResourceState.STARTED:
747                     t = rm.start_time
748                 elif state == ResourceState.STOPPED:
749                     t = rm.stop_time
750                 elif state == ResourceState.FINISHED:
751                     t = rm.finish_time
752                 elif state == ResourceState.RELEASED:
753                     t = rm.release_time
754                 else:
755                     break
756
757                 # time already elapsed since RM changed state
758                 waited = "%fs" % tdiffsec(tnow(), t)
759
760                 # time still to wait
761                 wait = tdiffsec(stabsformat(time), stabsformat(waited))
762
763                 if wait > 0.001:
764                     reschedule = True
765                     delay = "%fs" % wait
766                     break
767
768         return reschedule, delay
769
770     def set_with_conditions(self, name, value, group, state, time):
771         """ Set value 'value' on attribute with name 'name' when 'time' 
772         has elapsed since all elements in 'group' have reached state
773         'state'
774
775         :param name: Name of the attribute to set
776         :type name: str
777         :param name: Value of the attribute to set
778         :type name: str
779         :param group: Group of RMs to wait for (list of guids)
780         :type group: int or list of int
781         :param state: State to wait for on all RM in group. (either 'STARTED', 'STOPPED' or 'READY')
782         :type state: str
783         :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
784         :type time: str
785         """
786
787         reschedule = False
788         delay = reschedule_delay 
789
790         ## evaluate if set conditions are met
791
792         # only can set with conditions after the RM is started
793         if self.state != ResourceState.STARTED:
794             reschedule = True
795         else:
796             reschedule, delay = self._needs_reschedule(group, state, time)
797
798         if reschedule:
799             callback = functools.partial(self.set_with_conditions, 
800                     name, value, group, state, time)
801             self.ec.schedule(delay, callback)
802         else:
803             self.set(name, value)
804
805     def start_with_conditions(self):
806         """ Starts RM when all the conditions in self.conditions for
807         action 'START' are satisfied.
808
809         """
810         reschedule = False
811         delay = reschedule_delay 
812
813         ## evaluate if conditions to start are met
814         if self.ec.abort:
815             return 
816
817         # Can only start when RM is either STOPPED or READY
818         if self.state not in [ResourceState.STOPPED, ResourceState.READY]:
819             reschedule = True
820             self.debug("---- RESCHEDULING START ---- state %s " % self.state )
821         else:
822             start_conditions = self.conditions.get(ResourceAction.START, [])
823             
824             self.debug("---- START CONDITIONS ---- %s" % start_conditions) 
825             
826             # Verify all start conditions are met
827             for (group, state, time) in start_conditions:
828                 # Uncomment for debug
829                 #unmet = []
830                 #for guid in group:
831                 #    rm = self.ec.get_resource(guid)
832                 #    unmet.append((guid, rm._state))
833                 #
834                 #self.debug("---- WAITED STATES ---- %s" % unmet )
835
836                 reschedule, delay = self._needs_reschedule(group, state, time)
837                 if reschedule:
838                     break
839
840         if reschedule:
841             self.ec.schedule(delay, self.start_with_conditions)
842         else:
843             self.debug("----- STARTING ---- ")
844             self.start()
845
846     def stop_with_conditions(self):
847         """ Stops RM when all the conditions in self.conditions for
848         action 'STOP' are satisfied.
849
850         """
851         reschedule = False
852         delay = reschedule_delay 
853
854         ## evaluate if conditions to stop are met
855         if self.ec.abort:
856             return 
857
858         # only can stop when RM is STARTED
859         if self.state != ResourceState.STARTED:
860             reschedule = True
861             self.debug("---- RESCHEDULING STOP ---- state %s " % self.state )
862         else:
863             self.debug(" ---- STOP CONDITIONS ---- %s" % 
864                     self.conditions.get(ResourceAction.STOP))
865
866             stop_conditions = self.conditions.get(ResourceAction.STOP, []) 
867             for (group, state, time) in stop_conditions:
868                 reschedule, delay = self._needs_reschedule(group, state, time)
869                 if reschedule:
870                     break
871
872         if reschedule:
873             callback = functools.partial(self.stop_with_conditions)
874             self.ec.schedule(delay, callback)
875         else:
876             self.debug(" ----- STOPPING ---- ") 
877             self.stop()
878
879     def deploy_with_conditions(self):
880         """ Deploy RM when all the conditions in self.conditions for
881         action 'READY' are satisfied.
882
883         """
884         reschedule = False
885         delay = reschedule_delay 
886
887         ## evaluate if conditions to deploy are met
888         if self.ec.abort:
889             return 
890
891         # only can deploy when RM is either NEW, DISCOVERED or PROVISIONED 
892         if self.state not in [ResourceState.NEW, ResourceState.DISCOVERED, 
893                 ResourceState.PROVISIONED]:
894             reschedule = True
895             self.debug("---- RESCHEDULING DEPLOY ---- state %s " % self.state )
896         else:
897             deploy_conditions = self.conditions.get(ResourceAction.DEPLOY, [])
898             
899             self.debug("---- DEPLOY CONDITIONS ---- %s" % deploy_conditions) 
900             
901             # Verify all start conditions are met
902             for (group, state, time) in deploy_conditions:
903                 # Uncomment for debug
904                 #unmet = []
905                 #for guid in group:
906                 #    rm = self.ec.get_resource(guid)
907                 #    unmet.append((guid, rm._state))
908                 #
909                 #self.debug("---- WAITED STATES ---- %s" % unmet )
910
911                 reschedule, delay = self._needs_reschedule(group, state, time)
912                 if reschedule:
913                     break
914
915         if reschedule:
916             self.ec.schedule(delay, self.deploy_with_conditions)
917         else:
918             self.debug("----- STARTING ---- ")
919             self.deploy()
920
921     def do_connect(self, guid):
922         """ Performs actions that need to be taken upon associating RMs.
923         This method should be redefined when necessary in child classes.
924         """
925         pass
926
927     def do_disconnect(self, guid):
928         """ Performs actions that need to be taken upon disassociating RMs.
929         This method should be redefined when necessary in child classes.
930         """
931         pass
932
933     def valid_connection(self, guid):
934         """Checks whether a connection with the other RM
935         is valid.
936         This method need to be redefined by each new Resource Manager.
937
938         :param guid: Guid of the current Resource Manager
939         :type guid: int
940         :rtype:  Boolean
941
942         """
943         # TODO: Validate!
944         return True
945
946     def do_discover(self):
947         self.set_discovered()
948
949     def do_provision(self):
950         self.set_provisioned()
951
952     def do_start(self):
953         self.set_started()
954
955     def do_stop(self):
956         self.set_stopped()
957
958     def do_deploy(self):
959         self.set_ready()
960
961     def do_release(self):
962         pass
963
964     def do_finish(self):
965         # In case the RM passed from STARTED directly to FINISHED,
966         # we set the stop_time for consistency
967         if self.stop_time == None:
968             self.set_stopped()
969
970         self.set_finished()
971
972     def do_fail(self):
973         self.set_failed()
974
975     def set_started(self):
976         """ Mark ResourceManager as STARTED """
977         self.set_state(ResourceState.STARTED, "_start_time")
978         
979     def set_stopped(self):
980         """ Mark ResourceManager as STOPPED """
981         self.set_state(ResourceState.STOPPED, "_stop_time")
982
983     def set_ready(self):
984         """ Mark ResourceManager as READY """
985         self.set_state(ResourceState.READY, "_ready_time")
986
987     def set_released(self):
988         """ Mark ResourceManager as REALEASED """
989         self.set_state(ResourceState.RELEASED, "_release_time")
990
991     def set_finished(self):
992         """ Mark ResourceManager as FINISHED """
993         self.set_state(ResourceState.FINISHED, "_finish_time")
994
995     def set_failed(self):
996         """ Mark ResourceManager as FAILED """
997         self.set_state(ResourceState.FAILED, "_failed_time")
998
999     def set_discovered(self):
1000         """ Mark ResourceManager as DISCOVERED """
1001         self.set_state(ResourceState.DISCOVERED, "_discover_time")
1002
1003     def set_provisioned(self):
1004         """ Mark ResourceManager as PROVISIONED """
1005         self.set_state(ResourceState.PROVISIONED, "_provision_time")
1006
1007     def set_state(self, state, state_time_attr):
1008         # Ensure that RM state will not change after released
1009         if self._state == ResourceState.RELEASED:
1010             return 
1011    
1012         setattr(self, state_time_attr, tnow())
1013         self._state = state
1014
1015 class ResourceFactory(object):
1016     _resource_types = dict()
1017
1018     @classmethod
1019     def resource_types(cls):
1020         """Return the type of the Class"""
1021         return cls._resource_types
1022
1023     @classmethod
1024     def get_resource_type(cls, rtype):
1025         """Return the type of the Class"""
1026         return cls._resource_types.get(rtype)
1027
1028     @classmethod
1029     def register_type(cls, rclass):
1030         """Register a new Ressource Manager"""
1031         cls._resource_types[rclass.rtype()] = rclass
1032
1033     @classmethod
1034     def create(cls, rtype, ec, guid):
1035         """Create a new instance of a Ressource Manager"""
1036         rclass = cls._resource_types[rtype]
1037         return rclass(ec, guid)
1038
1039 def populate_factory():
1040     """Register all the possible RM that exists in the current version of Nepi.
1041     """
1042     # Once the factory is populated, don't repopulate
1043     if not ResourceFactory.resource_types():
1044         for rclass in find_types():
1045             ResourceFactory.register_type(rclass)
1046
1047 def find_types():
1048     """Look into the different folders to find all the 
1049     availables Resources Managers
1050     """
1051     search_path = os.environ.get("NEPI_SEARCH_PATH", "")
1052     search_path = set(search_path.split(" "))
1053    
1054     import inspect
1055     import nepi.resources 
1056     path = os.path.dirname(nepi.resources.__file__)
1057     search_path.add(path)
1058
1059     types = []
1060
1061     for importer, modname, ispkg in pkgutil.walk_packages(search_path, 
1062             prefix = "nepi.resources."):
1063
1064         loader = importer.find_module(modname)
1065         
1066         try:
1067             # Notice: Repeated calls to load_module will act as a reload of teh module
1068             if modname in sys.modules:
1069                 module = sys.modules.get(modname)
1070             else:
1071                 module = loader.load_module(modname)
1072
1073             for attrname in dir(module):
1074                 if attrname.startswith("_"):
1075                     continue
1076
1077                 attr = getattr(module, attrname)
1078
1079                 if attr == ResourceManager:
1080                     continue
1081
1082                 if not inspect.isclass(attr):
1083                     continue
1084
1085                 if issubclass(attr, ResourceManager):
1086                     types.append(attr)
1087
1088                     if not modname in sys.modules:
1089                         sys.modules[modname] = module
1090
1091         except:
1092             import traceback
1093             import logging
1094             err = traceback.format_exc()
1095             logger = logging.getLogger("Resource.find_types()")
1096             logger.error("Error while loading Resource Managers %s" % err)
1097
1098     return types
1099
1100