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 import guid
21 from nepi.util.parallel import ParallelRun
22 from nepi.util.timefuncs import tnow, tdiffsec, stabsformat, tsformat
23 from nepi.execution.resource import ResourceFactory, ResourceAction, \
24 ResourceState, ResourceState2str
25 from nepi.execution.scheduler import HeapScheduler, Task, TaskStatus
26 from nepi.execution.trace import TraceAttr
28 # TODO: use multiprocessing instead of threading
29 # TODO: Allow to reconnect to a running experiment instance! (reconnect mode vs deploy mode)
39 class FailureLevel(object):
40 """ Describes the system failure state """
45 class FailureManager(object):
46 """ The FailureManager is responsible for handling errors
47 and deciding whether an experiment should be aborted or not
51 def __init__(self, ec):
52 self._ec = weakref.ref(ec)
53 self._failure_level = FailureLevel.OK
57 """ Returns the ExperimentController associated to this FailureManager
65 if self._failure_level == FailureLevel.OK:
66 for guid in self.ec.resources:
68 state = self.ec.state(guid)
69 critical = self.ec.get(guid, "critical")
70 if state == ResourceState.FAILED and critical:
71 self._failure_level = FailureLevel.RM_FAILURE
72 self.ec.logger.debug("RM critical failure occurred on guid %d." \
73 " Setting EC FAILURE LEVEL to RM_FAILURE" % guid)
76 # An error might occure because a RM was deleted abruptly.
77 # In this case the error should be ignored.
78 if guid in self.ec._resources:
81 return self._failure_level != FailureLevel.OK
83 def set_ec_failure(self):
84 self._failure_level = FailureLevel.EC_FAILURE
86 class ECState(object):
87 """ Possible states for an ExperimentController
94 class ExperimentController(object):
96 .. class:: Class Args :
98 :param exp_id: Human readable identifier for the experiment scenario.
103 An experiment, or scenario, is defined by a concrete set of resources,
104 behavior, configuration and interconnection of those resources.
105 The Experiment Description (ED) is a detailed representation of a
106 single experiment. It contains all the necessary information to
107 allow repeating the experiment. NEPI allows to describe
108 experiments by registering components (resources), configuring them
109 and interconnecting them.
111 A same experiment (scenario) can be executed many times, generating
112 different results. We call an experiment execution (instance) a 'run'.
114 The ExperimentController (EC), is the entity responsible of
115 managing an experiment run. The same scenario can be
116 recreated (and re-run) by instantiating an EC and recreating
117 the same experiment description.
119 In NEPI, an experiment is represented as a graph of interconnected
120 resources. A resource is a generic concept in the sense that any
121 component taking part of an experiment, whether physical of
122 virtual, is considered a resource. A resources could be a host,
123 a virtual machine, an application, a simulator, a IP address.
125 A ResourceManager (RM), is the entity responsible for managing a
126 single resource. ResourceManagers are specific to a resource
127 type (i.e. An RM to control a Linux application will not be
128 the same as the RM used to control a ns-3 simulation).
129 To support a new type of resource in NEPI, a new RM must be
130 implemented. NEPI already provides a variety of
131 RMs to control basic resources, and new can be extended from
134 Through the EC interface the user can create ResourceManagers (RMs),
135 configure them and interconnect them, to describe an experiment.
136 Describing an experiment through the EC does not run the experiment.
137 Only when the 'deploy()' method is invoked on the EC, the EC will take
138 actions to transform the 'described' experiment into a 'running' experiment.
140 While the experiment is running, it is possible to continue to
141 create/configure/connect RMs, and to deploy them to involve new
142 resources in the experiment (this is known as 'interactive' deployment).
144 An experiments in NEPI is identified by a string id,
145 which is either given by the user, or automatically generated by NEPI.
146 The purpose of this identifier is to separate files and results that
147 belong to different experiment scenarios.
148 However, since a same 'experiment' can be run many times, the experiment
149 id is not enough to identify an experiment instance (run).
150 For this reason, the ExperimentController has two identifier, the
151 exp_id, which can be re-used in different ExperimentController,
152 and the run_id, which is unique to one ExperimentController instance, and
153 is automatically generated by NEPI.
157 def __init__(self, exp_id = None):
158 super(ExperimentController, self).__init__()
161 self._logger = logging.getLogger("ExperimentController")
163 # Run identifier. It identifies a concrete execution instance (run)
165 # Since a same experiment (same configuration) can be executed many
166 # times, this run_id permits to separate result files generated on
167 # different experiment executions
168 self._run_id = tsformat()
170 # Experiment identifier. Usually assigned by the user
171 # Identifies the experiment scenario (i.e. configuration,
172 # resources used, etc)
173 self._exp_id = exp_id or "exp-%s" % os.urandom(8).encode('hex')
175 # generator of globally unique ids
176 self._guid_generator = guid.GuidGenerator()
179 self._resources = dict()
181 # Scheduler. It a queue that holds tasks scheduled for
182 # execution, and yields the next task to be executed
183 # ordered by execution and arrival time
184 self._scheduler = HeapScheduler()
189 # RM groups (for deployment)
190 self._groups = dict()
192 # generator of globally unique id for groups
193 self._group_id_generator = guid.GuidGenerator()
195 # Flag to stop processing thread
198 # Entity in charge of managing system failures
199 self._fm = FailureManager(self)
202 self._state = ECState.RUNNING
204 # The runner is a pool of threads used to parallelize
206 nthreads = int(os.environ.get("NEPI_NTHREADS", "20"))
207 self._runner = ParallelRun(maxthreads = nthreads)
209 # Event processing thread
210 self._cond = threading.Condition()
211 self._thread = threading.Thread(target = self._process)
212 self._thread.setDaemon(True)
217 """ Returns the logger instance of the Experiment Controller
223 def failure_level(self):
224 """ Returns the level of FAILURE of th experiment
228 return self._fm._failure_level
232 """ Returns the state of the Experiment Controller
239 """ Returns the experiment id assigned by the user
246 """ Returns the experiment instance (run) identifier (automatically
254 """ Returns True if the experiment has failed and should be interrupted,
258 return self._fm.abort
260 def wait_finished(self, guids):
261 """ Blocking method that waits until all RMs in the 'guids' list
262 have reached a state >= STOPPED (i.e. STOPPED, FAILED or
263 RELEASED ), or until a failure in the experiment occurs
266 :param guids: List of guids
274 return self.wait(guids, state = ResourceState.STOPPED,
277 def wait_started(self, guids):
278 """ Blocking method that waits until all RMs in the 'guids' list
279 have reached a state >= STARTED, or until a failure in the
280 experiment occurs (i.e. abort == True)
282 :param guids: List of guids
290 return self.wait(guids, state = ResourceState.STARTED,
293 def wait_released(self, guids):
294 """ Blocking method that waits until all RMs in the 'guids' list
295 have reached a state == RELEASED, or until the EC fails
297 :param guids: List of guids
303 return self._state == ECState.FAILED
305 return self.wait(guids, state = ResourceState.RELEASED,
308 def wait_deployed(self, guids):
309 """ Blocking method that waits until all RMs in the 'guids' list
310 have reached a state >= READY, or until a failure in the
311 experiment occurs (i.e. abort == True)
313 :param guids: List of guids
321 return self.wait(guids, state = ResourceState.READY,
324 def wait(self, guids, state, quit):
325 """ Blocking method that waits until all RMs in the 'guids' list
326 have reached a state >= 'state', or until the 'quit' callback
329 :param guids: List of guids
333 if isinstance(guids, int):
336 # Make a copy to avoid modifying the original guids list
340 # If there are no more guids to wait for
341 # or the quit function returns True, exit the loop
342 if len(guids) == 0 or quit():
345 # If a guid reached one of the target states, remove it from list
347 rstate = self.state(guid)
349 hrrstate = ResourceState2str.get(rstate)
350 hrstate = ResourceState2str.get(state)
354 rm = self.get_resource(guid)
355 self.logger.debug(" %s guid %d DONE - state is %s, required is >= %s " % (
356 rm.get_rtype(), guid, hrrstate, hrstate))
359 self.logger.debug(" WAITING FOR guid %d - state is %s, required is >= %s " % (
360 guid, hrrstate, hrstate))
363 def get_task(self, tid):
364 """ Returns a task by its id
366 :param tid: Id of the task
372 return self._tasks.get(tid)
374 def get_resource(self, guid):
375 """ Returns a registered ResourceManager by its guid
377 :param guid: Id of the task
380 :rtype: ResourceManager
383 rm = self._resources.get(guid)
386 def remove_resource(self, guid):
387 del self._resources[guid]
391 """ Returns the set() of guids of all the ResourceManager
393 :return: Set of all RM guids
397 keys = self._resources.keys()
401 def register_resource(self, rtype, guid = None):
402 """ Registers a new ResourceManager of type 'rtype' in the experiment
404 This method will assign a new 'guid' for the RM, if no guid
407 :param rtype: Type of the RM
410 :return: Guid of the RM
414 # Get next available guid
415 guid = self._guid_generator.next(guid)
418 rm = ResourceFactory.create(rtype, self, guid)
421 self._resources[guid] = rm
425 def get_attributes(self, guid):
426 """ Returns all the attributes of the RM with guid 'guid'
428 :param guid: Guid of the RM
431 :return: List of attributes
435 rm = self.get_resource(guid)
436 return rm.get_attributes()
438 def get_attribute(self, guid, name):
439 """ Returns the attribute 'name' of the RM with guid 'guid'
441 :param guid: Guid of the RM
444 :param name: Name of the attribute
447 :return: The attribute with name 'name'
451 rm = self.get_resource(guid)
452 return rm.get_attribute(name)
454 def register_connection(self, guid1, guid2):
455 """ Registers a connection between a RM with guid 'guid1'
456 and another RM with guid 'guid2'.
458 The order of the in which the two guids are provided is not
459 important, since the connection relationship is symmetric.
461 :param guid1: First guid to connect
462 :type guid1: ResourceManager
464 :param guid2: Second guid to connect
465 :type guid: ResourceManager
468 rm1 = self.get_resource(guid1)
469 rm2 = self.get_resource(guid2)
471 rm1.register_connection(guid2)
472 rm2.register_connection(guid1)
474 def register_condition(self, guids1, action, guids2, state,
476 """ Registers an action START, STOP or DEPLOY for all RM on list
477 guids1 to occur at time 'time' after all elements in list guids2
478 have reached state 'state'.
480 :param guids1: List of guids of RMs subjected to action
483 :param action: Action to perform (either START, STOP or DEPLOY)
484 :type action: ResourceAction
486 :param guids2: List of guids of RMs to we waited for
489 :param state: State to wait for on RMs of list guids2 (STARTED,
491 :type state: ResourceState
493 :param time: Time to wait after guids2 has reached status
497 if isinstance(guids1, int):
499 if isinstance(guids2, int):
503 rm = self.get_resource(guid1)
504 rm.register_condition(action, guids2, state, time)
506 def enable_trace(self, guid, name):
507 """ Enables a trace to be collected during the experiment run
509 :param name: Name of the trace
513 rm = self.get_resource(guid)
514 rm.enable_trace(name)
516 def trace_enabled(self, guid, name):
517 """ Returns True if the trace of name 'name' is enabled
519 :param name: Name of the trace
523 rm = self.get_resource(guid)
524 return rm.trace_enabled(name)
526 def trace(self, guid, name, attr = TraceAttr.ALL, block = 512, offset = 0):
527 """ Returns information on a collected trace, the trace stream or
528 blocks (chunks) of the trace stream
530 :param name: Name of the trace
533 :param attr: Can be one of:
534 - TraceAttr.ALL (complete trace content),
535 - TraceAttr.STREAM (block in bytes to read starting
537 - TraceAttr.PATH (full path to the trace file),
538 - TraceAttr.SIZE (size of trace file).
541 :param block: Number of bytes to retrieve from trace, when attr is
545 :param offset: Number of 'blocks' to skip, when attr is TraceAttr.STREAM
551 rm = self.get_resource(guid)
552 return rm.trace(name, attr, block, offset)
554 def get_traces(self, guid):
555 """ Returns the list of the trace names of the RM with guid 'guid'
557 :param guid: Guid of the RM
560 :return: List of trace names
564 rm = self.get_resource(guid)
565 return rm.get_traces()
568 def discover(self, guid):
569 """ Discovers an available resource matching the criteria defined
570 by the RM with guid 'guid', and associates that resource to the RM
572 Not all RM types require (or are capable of) performing resource
573 discovery. For the RM types which are not capable of doing so,
574 invoking this method does not have any consequences.
576 :param guid: Guid of the RM
580 rm = self.get_resource(guid)
583 def provision(self, guid):
584 """ Provisions the resource associated to the RM with guid 'guid'.
586 Provisioning means making a resource 'accessible' to the user.
587 Not all RM types require (or are capable of) performing resource
588 provisioning. For the RM types which are not capable of doing so,
589 invoking this method does not have any consequences.
591 :param guid: Guid of the RM
595 rm = self.get_resource(guid)
596 return rm.provision()
598 def get(self, guid, name):
599 """ Returns the value of the attribute with name 'name' on the
602 :param guid: Guid of the RM
605 :param name: Name of the attribute
608 :return: The value of the attribute with name 'name'
611 rm = self.get_resource(guid)
614 def set(self, guid, name, value):
615 """ Modifies the value of the attribute with name 'name' on the
618 :param guid: Guid of the RM
621 :param name: Name of the attribute
624 :param value: Value of the attribute
627 rm = self.get_resource(guid)
630 def get_global(self, rtype, name):
631 """ Returns the value of the global attribute with name 'name' on the
632 RMs of rtype 'rtype'.
634 :param guid: Guid of the RM
637 :param name: Name of the attribute
640 :return: The value of the attribute with name 'name'
643 rclass = ResourceFactory.get_resource_type(rtype)
644 return rclass.get_global(name)
646 def set_global(self, rtype, name, value):
647 """ Modifies the value of the global attribute with name 'name' on the
648 RMs of with rtype 'rtype'.
650 :param guid: Guid of the RM
653 :param name: Name of the attribute
656 :param value: Value of the attribute
659 rclass = ResourceFactory.get_resource_type(rtype)
660 return rclass.set_global(name, value)
662 def state(self, guid, hr = False):
663 """ Returns the state of a resource
665 :param guid: Resource guid
668 :param hr: Human readable. Forces return of a
669 status string instead of a number
673 rm = self.get_resource(guid)
677 return ResourceState2str.get(state)
681 def stop(self, guid):
682 """ Stops the RM with guid 'guid'
684 Stopping a RM means that the resource it controls will
685 no longer take part of the experiment.
687 :param guid: Guid of the RM
691 rm = self.get_resource(guid)
694 def start(self, guid):
695 """ Starts the RM with guid 'guid'
697 Starting a RM means that the resource it controls will
698 begin taking part of the experiment.
700 :param guid: Guid of the RM
704 rm = self.get_resource(guid)
707 def get_start_time(self, guid):
708 """ Returns the start time of the RM as a timestamp """
709 rm = self.get_resource(guid)
712 def get_stop_time(self, guid):
713 """ Returns the stop time of the RM as a timestamp """
714 rm = self.get_resource(guid)
717 def get_discover_time(self, guid):
718 """ Returns the discover time of the RM as a timestamp """
719 rm = self.get_resource(guid)
720 return rm.discover_time
722 def get_provision_time(self, guid):
723 """ Returns the provision time of the RM as a timestamp """
724 rm = self.get_resource(guid)
725 return rm.provision_time
727 def get_ready_time(self, guid):
728 """ Returns the deployment time of the RM as a timestamp """
729 rm = self.get_resource(guid)
732 def get_release_time(self, guid):
733 """ Returns the release time of the RM as a timestamp """
734 rm = self.get_resource(guid)
735 return rm.release_time
737 def get_failed_time(self, guid):
738 """ Returns the time failure occured for the RM as a timestamp """
739 rm = self.get_resource(guid)
740 return rm.failed_time
742 def set_with_conditions(self, name, value, guids1, guids2, state,
744 """ Modifies the value of attribute with name 'name' on all RMs
745 on the guids1 list when time 'time' has elapsed since all
746 elements in guids2 list have reached state 'state'.
748 :param name: Name of attribute to set in RM
751 :param value: Value of attribute to set in RM
754 :param guids1: List of guids of RMs subjected to action
757 :param action: Action to register (either START or STOP)
758 :type action: ResourceAction
760 :param guids2: List of guids of RMs to we waited for
763 :param state: State to wait for on RMs (STARTED, STOPPED, etc)
764 :type state: ResourceState
766 :param time: Time to wait after guids2 has reached status
770 if isinstance(guids1, int):
772 if isinstance(guids2, int):
776 rm = self.get_resource(guid)
777 rm.set_with_conditions(name, value, guids2, state, time)
779 def deploy(self, guids = None, wait_all_ready = True, group = None):
780 """ Deploys all ResourceManagers in the guids list.
782 If the argument 'guids' is not given, all RMs with state NEW
785 :param guids: List of guids of RMs to deploy
788 :param wait_all_ready: Wait until all RMs are ready in
789 order to start the RMs
792 :param group: Id of deployment group in which to deploy RMs
796 self.logger.debug(" ------- DEPLOY START ------ ")
799 # If no guids list was passed, all 'NEW' RMs will be deployed
801 for guid in self.resources:
802 if self.state(guid) == ResourceState.NEW:
805 if isinstance(guids, int):
808 # Create deployment group
809 # New guids can be added to a same deployment group later on
813 group = self._group_id_generator.next()
815 if group not in self._groups:
816 self._groups[group] = []
818 self._groups[group].extend(guids)
820 def wait_all_and_start(group):
821 # Function that checks if all resources are READY
822 # before scheduling a start_with_conditions for each RM
825 # Get all guids in group
826 guids = self._groups[group]
829 if self.state(guid) < ResourceState.READY:
834 callback = functools.partial(wait_all_and_start, group)
835 self.schedule("1s", callback)
837 # If all resources are ready, we schedule the start
839 rm = self.get_resource(guid)
840 self.schedule("0s", rm.start_with_conditions)
842 if rm.conditions.get(ResourceAction.STOP):
843 # Only if the RM has STOP conditions we
844 # schedule a stop. Otherwise the RM will stop immediately
845 self.schedule("0s", rm.stop_with_conditions)
847 if wait_all_ready and new_group:
848 # Schedule a function to check that all resources are
849 # READY, and only then schedule the start.
850 # This aims at reducing the number of tasks looping in the
852 # Instead of having many start tasks, we will have only one for
854 callback = functools.partial(wait_all_and_start, group)
855 self.schedule("0s", callback)
858 rm = self.get_resource(guid)
859 rm.deployment_group = group
860 self.schedule("0s", rm.deploy_with_conditions)
862 if not wait_all_ready:
863 self.schedule("0s", rm.start_with_conditions)
865 if rm.conditions.get(ResourceAction.STOP):
866 # Only if the RM has STOP conditions we
867 # schedule a stop. Otherwise the RM will stop immediately
868 self.schedule("0s", rm.stop_with_conditions)
870 def release(self, guids = None):
871 """ Releases all ResourceManagers in the guids list.
873 If the argument 'guids' is not given, all RMs registered
874 in the experiment are released.
876 :param guids: List of RM guids
880 if isinstance(guids, int):
884 guids = self.resources
887 rm = self.get_resource(guid)
888 self.schedule("0s", rm.release)
890 self.wait_released(guids)
893 if self.get(guid, "hardRelease"):
894 self.remove_resource(guid)
897 """ Releases all resources and stops the ExperimentController
900 # If there was a major failure we can't exit gracefully
901 if self._state == ECState.FAILED:
902 raise RuntimeError("EC failure. Can not exit gracefully")
904 # Remove all pending tasks from the scheduler queue
905 for tid in list(self._scheduler.pending):
906 self._scheduler.remove(tid)
908 # Remove pending tasks from the workers queue
913 # Mark the EC state as TERMINATED
914 self._state = ECState.TERMINATED
916 # Stop processing thread
919 # Notify condition to wake up the processing thread
922 if self._thread.is_alive():
925 def schedule(self, date, callback, track = False):
926 """ Schedules a callback to be executed at time 'date'.
928 :param date: string containing execution time for the task.
929 It can be expressed as an absolute time, using
930 timestamp format, or as a relative time matching
931 ^\d+.\d+(h|m|s|ms|us)$
933 :param callback: code to be executed for the task. Must be a
934 Python function, and receives args and kwargs
937 :param track: if set to True, the task will be retrievable with
938 the get_task() method
940 :return : The Id of the task
944 timestamp = stabsformat(date)
945 task = Task(timestamp, callback)
946 task = self._scheduler.schedule(task)
949 self._tasks[task.id] = task
951 # Notify condition to wake up the processing thread
957 """ Process scheduled tasks.
961 Tasks are scheduled by invoking the schedule method with a target
962 callback and an execution time.
963 The schedule method creates a new Task object with that callback
964 and execution time, and pushes it into the '_scheduler' queue.
965 The execution time and the order of arrival of tasks are used
966 to order the tasks in the queue.
968 The _process method is executed in an independent thread held by
969 the ExperimentController for as long as the experiment is running.
970 This method takes tasks from the '_scheduler' queue in a loop
971 and processes them in parallel using multithreading.
972 The environmental variable NEPI_NTHREADS can be used to control
973 the number of threads used to process tasks. The default value is
976 To execute tasks in parallel, a ParallelRunner (PR) object is used.
977 This object keeps a pool of threads (workers), and a queue of tasks
978 scheduled for 'immediate' execution.
980 On each iteration, the '_process' loop will take the next task that
981 is scheduled for 'future' execution from the '_scheduler' queue,
982 and if the execution time of that task is >= to the current time,
983 it will push that task into the PR for 'immediate execution'.
984 As soon as a worker is free, the PR will assign the next task to
987 Upon receiving a task to execute, each PR worker (thread) will
988 invoke the _execute method of the EC, passing the task as
990 The _execute method will then invoke task.callback inside a
991 try/except block. If an exception is raised by the tasks.callback,
992 it will be trapped by the try block, logged to standard error
993 (usually the console), and the task will be marked as failed.
999 while not self._stop:
1001 self._cond.acquire()
1003 task = self._scheduler.next()
1006 # No task to execute. Wait for a new task to be scheduled.
1009 # The task timestamp is in the future. Wait for timeout
1010 # or until another task is scheduled.
1012 if now < task.timestamp:
1013 # Calculate timeout in seconds
1014 timeout = tdiffsec(task.timestamp, now)
1016 # Re-schedule task with the same timestamp
1017 self._scheduler.schedule(task)
1021 # Wait timeout or until a new task awakes the condition
1022 self._cond.wait(timeout)
1024 self._cond.release()
1027 # Process tasks in parallel
1028 self._runner.put(self._execute, task)
1031 err = traceback.format_exc()
1032 self.logger.error("Error while processing tasks in the EC: %s" % err)
1034 # Set the EC to FAILED state
1035 self._state = ECState.FAILED
1037 # Set the FailureManager failure level to EC failure
1038 self._fm.set_ec_failure()
1040 self.logger.debug("Exiting the task processing loop ... ")
1043 self._runner.destroy()
1045 def _execute(self, task):
1046 """ Executes a single task.
1048 :param task: Object containing the callback to execute
1054 task.result = task.callback()
1055 task.status = TaskStatus.DONE
1058 err = traceback.format_exc()
1060 task.status = TaskStatus.ERROR
1062 self.logger.error("Error occurred while executing task: %s" % err)
1065 """ Awakes the processing thread if it is blocked waiting
1066 for new tasks to arrive
1069 self._cond.acquire()
1071 self._cond.release()