1 from neco.util.timefuncs import strfnow, strfdiff, strfvalid
2 from neco.execution.trace import TraceAttr
9 _reschedule_delay = "1s"
31 # Decorator to invoke class initialization method
33 class ResourceManager(object):
40 def _register_filter(cls, attr):
41 """ Resource subclasses will invoke this method to add a
45 cls._filters[attr.name] = attr
48 def _register_attribute(cls, attr):
49 """ Resource subclasses will invoke this method to add a
53 cls._attributes[attr.name] = attr
56 def _register_trace(cls, trace):
57 """ Resource subclasses will invoke this method to add a
61 cls._traces[trace.name] = trace
65 def _register_filters(cls):
66 """ Resource subclasses will invoke this method to register
73 def _register_attributes(cls):
74 """ Resource subclasses will invoke this method to register
81 def _register_traces(cls):
82 """ Resource subclasses will invoke this method to register
90 """ Create a new dictionnary instance of the dictionnary
91 with the same template.
93 Each ressource should have the same registration dictionary
94 template with different instances.
96 # static template for resource filters
98 cls._register_filters()
100 # static template for resource attributes
101 cls._attributes = dict()
102 cls._register_attributes()
104 # static template for resource traces
106 cls._register_traces()
113 def get_filters(cls):
114 """ Returns a copy of the filters
117 return copy.deepcopy(cls._filters.values())
120 def get_attributes(cls):
121 """ Returns a copy of the attributes
124 return copy.deepcopy(cls._attributes.values())
128 """ Returns a copy of the traces
131 return copy.deepcopy(cls._traces.values())
133 def __init__(self, ec, guid):
135 self._ec = weakref.ref(ec)
136 self._connections = set()
137 self._conditions = dict()
139 # the resource instance gets a copy of all attributes
140 self._attrs = copy.deepcopy(self._attributes)
142 # the resource instance gets a copy of all traces
143 self._trcs = copy.deepcopy(self._traces)
145 self._state = ResourceState.NEW
147 self._start_time = None
148 self._stop_time = None
149 self._discover_time = None
150 self._provision_time = None
151 self._ready_time = None
152 self._release_time = None
155 self._logger = logging.getLogger("neco.execution.resource.Resource %s.%d " % (self._rtype, self.guid))
170 def connections(self):
171 return self._connections
174 def conditions(self):
175 return self._conditions
178 def start_time(self):
179 """ Returns timestamp with the time the RM started """
180 return self._start_time
184 """ Returns timestamp with the time the RM stopped """
185 return self._stop_time
188 def discover_time(self):
189 """ Returns timestamp with the time the RM passed to state discovered """
190 return self._discover_time
193 def provision_time(self):
194 """ Returns timestamp with the time the RM passed to state provisioned """
195 return self._provision_time
198 def ready_time(self):
199 """ Returns timestamp with the time the RM passed to state ready """
200 return self._ready_time
203 def release_time(self):
204 """ Returns timestamp with the time the RM was released """
205 return self._release_time
211 def connect(self, guid):
212 if self.valid_connection(guid):
213 self._connections.add(guid)
215 def discover(self, filters = None):
216 self._discover_time = strfnow()
217 self._state = ResourceState.DISCOVERED
219 def provision(self, filters = None):
220 self._provision_time = strfnow()
221 self._state = ResourceState.PROVISIONED
224 """ Start the Resource Manager
227 if not self._state in [ResourceState.READY, ResourceState.STOPPED]:
228 self.logger.error("Wrong state %s for start" % self.state)
231 self._start_time = strfnow()
232 self._state = ResourceState.STARTED
235 """ Start the Resource Manager
238 if not self._state in [ResourceState.STARTED]:
239 self.logger.error("Wrong state %s for stop" % self.state)
242 self._stop_time = strfnow()
243 self._state = ResourceState.STOPPED
245 def set(self, name, value):
246 """ Set the value of the attribute
248 :param name: Name of the attribute
250 :param name: Value of the attribute
253 attr = self._attrs[name]
257 """ Start the Resource Manager
259 :param name: Name of the attribute
263 attr = self._attrs[name]
266 def register_trace(self, name):
269 :param name: Name of the trace
272 trace = self._trcs[name]
275 def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
276 """ Get information on collected trace
278 :param name: Name of the trace
281 :param attr: Can be one of:
282 - TraceAttr.ALL (complete trace content),
283 - TraceAttr.STREAM (block in bytes to read starting at offset),
284 - TraceAttr.PATH (full path to the trace file),
285 - TraceAttr.SIZE (size of trace file).
288 :param block: Number of bytes to retrieve from trace, when attr is TraceAttr.STREAM
291 :param offset: Number of 'blocks' to skip, when attr is TraceAttr.STREAM
298 def register_condition(self, action, group, state,
300 """ Registers a condition on the resource manager to allow execution
301 of 'action' only after 'time' has elapsed from the moment all resources
302 in 'group' reached state 'state'
304 :param action: Action to restrict to condition (either 'START' or 'STOP')
306 :param group: Group of RMs to wait for (list of guids)
307 :type group: int or list of int
308 :param state: State to wait for on all RM in group. (either 'STARTED' or 'STOPPED')
310 :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
314 conditions = self.conditions.get(action)
317 self._conditions[action] = conditions
319 # For each condition to register a tuple of (group, state, time) is
320 # added to the 'action' list
321 if not isinstance(group, list):
324 conditions.append((group, state, time))
326 def get_connected(self, rtype):
328 for guid in self.connections:
329 rm = self.ec.get_resource(guid)
330 if rm.rtype() == rtype:
334 def _needs_reschedule(self, group, state, time):
335 """ Internal method that verify if 'time' has elapsed since
336 all elements in 'group' have reached state 'state'.
338 :param group: Group of RMs to wait for (list of guids)
339 :type group: int or list of int
340 :param state: State to wait for on all RM in group. (either 'STARTED' or 'STOPPED')
342 :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
345 .. note : time should be written like "2s" or "3m" with s for seconds, m for minutes, h for hours, ...
346 If for example, you need to wait 2min 30sec, time could be "150s" or "2.5m".
347 For the moment, 2m30s is not a correct syntax.
351 delay = _reschedule_delay
353 # check state and time elapsed on all RMs
355 rm = self.ec.get_resource(guid)
356 # If the RM state is lower than the requested state we must
357 # reschedule (e.g. if RM is READY but we required STARTED)
362 # If there is a time restriction, we must verify the
363 # restriction is satisfied
365 if state == ResourceState.DISCOVERED:
367 if state == ResourceState.PROVISIONED:
368 t = rm.provision_time
369 elif state == ResourceState.READY:
371 elif state == ResourceState.STARTED:
373 elif state == ResourceState.STOPPED:
376 # Only keep time information for START and STOP
379 d = strfdiff(strfnow(), t)
380 wait = strfdiff(strfvalid(time),strfvalid(str(d)+"s"))
385 return reschedule, delay
387 def set_with_conditions(self, name, value, group, state, time):
388 """ Set value 'value' on attribute with name 'name' when 'time'
389 has elapsed since all elements in 'group' have reached state
392 :param name: Name of the attribute to set
394 :param name: Value of the attribute to set
396 :param group: Group of RMs to wait for (list of guids)
397 :type group: int or list of int
398 :param state: State to wait for on all RM in group. (either 'STARTED', 'STOPPED' or 'READY')
400 :param time: Time to wait after 'state' is reached on all RMs in group. (e.g. '2s')
406 delay = _reschedule_delay
408 ## evaluate if set conditions are met
410 # only can set with conditions after the RM is started
411 if self.state != ResourceState.STARTED:
414 reschedule, delay = self._needs_reschedule(group, state, time)
417 callback = functools.partial(self.set_with_conditions,
418 name, value, group, state, time)
419 self.ec.schedule(delay, callback)
421 self.set(name, value)
423 def start_with_conditions(self):
424 """ Starts RM when all the conditions in self.conditions for
425 action 'START' are satisfied.
429 delay = _reschedule_delay
431 ## evaluate if set conditions are met
433 # only can start when RM is either STOPPED or READY
434 if self.state not in [ResourceState.STOPPED, ResourceState.READY]:
436 self.logger.debug("---- RESCHEDULING START ---- state %s " % self.state )
438 self.logger.debug("---- START CONDITIONS ---- %s" %
439 self.conditions.get(ResourceAction.START))
441 # Verify all start conditions are met
442 start_conditions = self.conditions.get(ResourceAction.START, [])
443 for (group, state, time) in start_conditions:
444 reschedule, delay = self._needs_reschedule(group, state, time)
449 self.ec.schedule(delay, self.start_with_conditions)
451 self.logger.debug("----- STARTING ---- ")
454 def stop_with_conditions(self):
455 """ Stops RM when all the conditions in self.conditions for
456 action 'STOP' are satisfied.
460 delay = _reschedule_delay
462 ## evaluate if set conditions are met
464 # only can stop when RM is STARTED
465 if self.state != ResourceState.STARTED:
468 self.logger.debug(" ---- STOP CONDITIONS ---- %s" %
469 self.conditions.get(ResourceAction.STOP))
471 stop_conditions = self.conditions.get(ResourceAction.STOP, [])
472 for (group, state, time) in stop_conditions:
473 reschedule, delay = self._needs_reschedule(group, state, time)
478 callback = functools.partial(self.stop_with_conditions)
479 self.ec.schedule(delay, callback)
481 self.logger.debug(" ----- STOPPING ---- ")
485 """ Execute all steps required for the RM to reach the state READY
488 if self._state > ResourceState.READY:
489 self.logger.error("Wrong state %s for deploy" % self.state)
492 self._ready_time = strfnow()
493 self._state = ResourceState.READY
496 """Clean the resource at the end of the Experiment and change the status
499 self._release_time = strfnow()
500 self._state = ResourceState.RELEASED
502 def valid_connection(self, guid):
503 """Check if the connection is available.
505 :param guid: Guid of the current Resource Manager
513 class ResourceFactory(object):
514 _resource_types = dict()
517 def resource_types(cls):
518 return cls._resource_types
521 def register_type(cls, rclass):
522 cls._resource_types[rclass.rtype()] = rclass
525 def create(cls, rtype, ec, guid):
526 rclass = cls._resource_types[rtype]
527 return rclass(ec, guid)