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", "3"))
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
224 """ Returns the state of the Experiment Controller
231 """ Returns the experiment id assigned by the user
238 """ Returns the experiment instance (run) identifier (automatically
246 """ Returns True if the experiment has failed and should be interrupted,
250 return self._fm.abort
252 def wait_finished(self, guids):
253 """ Blocking method that waits until all RMs in the 'guids' list
254 have reached a state >= STOPPED (i.e. STOPPED, FAILED or
255 RELEASED ), or until a failure in the experiment occurs
258 :param guids: List of guids
266 return self.wait(guids, state = ResourceState.STOPPED,
269 def wait_started(self, guids):
270 """ Blocking method that waits until all RMs in the 'guids' list
271 have reached a state >= STARTED, or until a failure in the
272 experiment occurs (i.e. abort == True)
274 :param guids: List of guids
282 return self.wait(guids, state = ResourceState.STARTED,
285 def wait_released(self, guids):
286 """ Blocking method that waits until all RMs in the 'guids' list
287 have reached a state == RELEASED, or until the EC fails
289 :param guids: List of guids
295 return self._state == ECState.FAILED
297 return self.wait(guids, state = ResourceState.RELEASED,
300 def wait_deployed(self, guids):
301 """ Blocking method that waits until all RMs in the 'guids' list
302 have reached a state >= READY, or until a failure in the
303 experiment occurs (i.e. abort == True)
305 :param guids: List of guids
313 return self.wait(guids, state = ResourceState.READY,
316 def wait(self, guids, state, quit):
317 """ Blocking method that waits until all RMs in the 'guids' list
318 have reached a state >= 'state', or until the 'quit' callback
321 :param guids: List of guids
325 if isinstance(guids, int):
328 # Make a copy to avoid modifying the original guids list
332 # If there are no more guids to wait for
333 # or the quit function returns True, exit the loop
334 if len(guids) == 0 or quit():
337 # If a guid reached one of the target states, remove it from list
339 rstate = self.state(guid)
341 hrrstate = ResourceState2str.get(rstate)
342 hrstate = ResourceState2str.get(state)
346 rm = self.get_resource(guid)
347 self.logger.debug(" %s guid %d DONE - state is %s, required is >= %s " % (
348 rm.get_rtype(), guid, hrrstate, hrstate))
351 self.logger.debug(" WAITING FOR guid %d - state is %s, required is >= %s " % (
352 guid, hrrstate, hrstate))
355 def get_task(self, tid):
356 """ Returns a task by its id
358 :param tid: Id of the task
364 return self._tasks.get(tid)
366 def get_resource(self, guid):
367 """ Returns a registered ResourceManager by its guid
369 :param guid: Id of the task
372 :rtype: ResourceManager
375 rm = self._resources.get(guid)
378 def remove_resource(self, guid):
379 del self._resources[guid]
383 """ Returns the set() of guids of all the ResourceManager
385 :return: Set of all RM guids
389 keys = self._resources.keys()
393 def register_resource(self, rtype, guid = None):
394 """ Registers a new ResourceManager of type 'rtype' in the experiment
396 This method will assign a new 'guid' for the RM, if no guid
399 :param rtype: Type of the RM
402 :return: Guid of the RM
406 # Get next available guid
407 guid = self._guid_generator.next(guid)
410 rm = ResourceFactory.create(rtype, self, guid)
413 self._resources[guid] = rm
417 def get_attributes(self, guid):
418 """ Returns all the attributes of the RM with guid 'guid'
420 :param guid: Guid of the RM
423 :return: List of attributes
427 rm = self.get_resource(guid)
428 return rm.get_attributes()
430 def get_attribute(self, guid, name):
431 """ Returns the attribute 'name' of the RM with guid 'guid'
433 :param guid: Guid of the RM
436 :param name: Name of the attribute
439 :return: The attribute with name 'name'
443 rm = self.get_resource(guid)
444 return rm.get_attribute(name)
446 def register_connection(self, guid1, guid2):
447 """ Registers a connection between a RM with guid 'guid1'
448 and another RM with guid 'guid2'.
450 The order of the in which the two guids are provided is not
451 important, since the connection relationship is symmetric.
453 :param guid1: First guid to connect
454 :type guid1: ResourceManager
456 :param guid2: Second guid to connect
457 :type guid: ResourceManager
460 rm1 = self.get_resource(guid1)
461 rm2 = self.get_resource(guid2)
463 rm1.register_connection(guid2)
464 rm2.register_connection(guid1)
466 def register_condition(self, guids1, action, guids2, state,
468 """ Registers an action START, STOP or DEPLOY for all RM on list
469 guids1 to occur at time 'time' after all elements in list guids2
470 have reached state 'state'.
472 :param guids1: List of guids of RMs subjected to action
475 :param action: Action to perform (either START, STOP or DEPLOY)
476 :type action: ResourceAction
478 :param guids2: List of guids of RMs to we waited for
481 :param state: State to wait for on RMs of list guids2 (STARTED,
483 :type state: ResourceState
485 :param time: Time to wait after guids2 has reached status
489 if isinstance(guids1, int):
491 if isinstance(guids2, int):
495 rm = self.get_resource(guid1)
496 rm.register_condition(action, guids2, state, time)
498 def enable_trace(self, guid, name):
499 """ Enables a trace to be collected during the experiment run
501 :param name: Name of the trace
505 rm = self.get_resource(guid)
506 rm.enable_trace(name)
508 def trace_enabled(self, guid, name):
509 """ Returns True if the trace of name 'name' is enabled
511 :param name: Name of the trace
515 rm = self.get_resource(guid)
516 return rm.trace_enabled(name)
518 def trace(self, guid, name, attr = TraceAttr.ALL, block = 512, offset = 0):
519 """ Returns information on a collected trace, the trace stream or
520 blocks (chunks) of the trace stream
522 :param name: Name of the trace
525 :param attr: Can be one of:
526 - TraceAttr.ALL (complete trace content),
527 - TraceAttr.STREAM (block in bytes to read starting
529 - TraceAttr.PATH (full path to the trace file),
530 - TraceAttr.SIZE (size of trace file).
533 :param block: Number of bytes to retrieve from trace, when attr is
537 :param offset: Number of 'blocks' to skip, when attr is TraceAttr.STREAM
543 rm = self.get_resource(guid)
544 return rm.trace(name, attr, block, offset)
546 def get_traces(self, guid):
547 """ Returns the list of the trace names of the RM with guid 'guid'
549 :param guid: Guid of the RM
552 :return: List of trace names
556 rm = self.get_resource(guid)
557 return rm.get_traces()
560 def discover(self, guid):
561 """ Discovers an available resource matching the criteria defined
562 by the RM with guid 'guid', and associates that resource to the RM
564 Not all RM types require (or are capable of) performing resource
565 discovery. For the RM types which are not capable of doing so,
566 invoking this method does not have any consequences.
568 :param guid: Guid of the RM
572 rm = self.get_resource(guid)
575 def provision(self, guid):
576 """ Provisions the resource associated to the RM with guid 'guid'.
578 Provisioning means making a resource 'accessible' to the user.
579 Not all RM types require (or are capable of) performing resource
580 provisioning. For the RM types which are not capable of doing so,
581 invoking this method does not have any consequences.
583 :param guid: Guid of the RM
587 rm = self.get_resource(guid)
588 return rm.provision()
590 def get(self, guid, name):
591 """ Returns the value of the attribute with name 'name' on the
594 :param guid: Guid of the RM
597 :param name: Name of the attribute
600 :return: The value of the attribute with name 'name'
603 rm = self.get_resource(guid)
606 def set(self, guid, name, value):
607 """ Modifies the value of the attribute with name 'name' on the
610 :param guid: Guid of the RM
613 :param name: Name of the attribute
616 :param value: Value of the attribute
619 rm = self.get_resource(guid)
622 def get_global(self, rtype, name):
623 """ Returns the value of the global attribute with name 'name' on the
624 RMs of rtype 'rtype'.
626 :param guid: Guid of the RM
629 :param name: Name of the attribute
632 :return: The value of the attribute with name 'name'
635 rclass = ResourceFactory.get_resource_type(rtype)
636 return rclass.get_global(name)
638 def set_global(self, rtype, name, value):
639 """ Modifies the value of the global attribute with name 'name' on the
640 RMs of with rtype 'rtype'.
642 :param guid: Guid of the RM
645 :param name: Name of the attribute
648 :param value: Value of the attribute
651 rclass = ResourceFactory.get_resource_type(rtype)
652 return rclass.set_global(name, value)
654 def state(self, guid, hr = False):
655 """ Returns the state of a resource
657 :param guid: Resource guid
660 :param hr: Human readable. Forces return of a
661 status string instead of a number
665 rm = self.get_resource(guid)
669 return ResourceState2str.get(state)
673 def stop(self, guid):
674 """ Stops the RM with guid 'guid'
676 Stopping a RM means that the resource it controls will
677 no longer take part of the experiment.
679 :param guid: Guid of the RM
683 rm = self.get_resource(guid)
686 def start(self, guid):
687 """ Starts the RM with guid 'guid'
689 Starting a RM means that the resource it controls will
690 begin taking part of the experiment.
692 :param guid: Guid of the RM
696 rm = self.get_resource(guid)
699 def get_start_time(self, guid):
700 """ Returns the start time of the RM as a timestamp """
701 rm = self.get_resource(guid)
704 def get_stop_time(self, guid):
705 """ Returns the stop time of the RM as a timestamp """
706 rm = self.get_resource(guid)
709 def get_discover_time(self, guid):
710 """ Returns the discover time of the RM as a timestamp """
711 rm = self.get_resource(guid)
712 return rm.discover_time
714 def get_provision_time(self, guid):
715 """ Returns the provision time of the RM as a timestamp """
716 rm = self.get_resource(guid)
717 return rm.provision_time
719 def get_ready_time(self, guid):
720 """ Returns the deployment time of the RM as a timestamp """
721 rm = self.get_resource(guid)
724 def get_release_time(self, guid):
725 """ Returns the release time of the RM as a timestamp """
726 rm = self.get_resource(guid)
727 return rm.release_time
729 def get_failed_time(self, guid):
730 """ Returns the time failure occured for the RM as a timestamp """
731 rm = self.get_resource(guid)
732 return rm.failed_time
734 def set_with_conditions(self, name, value, guids1, guids2, state,
736 """ Modifies the value of attribute with name 'name' on all RMs
737 on the guids1 list when time 'time' has elapsed since all
738 elements in guids2 list have reached state 'state'.
740 :param name: Name of attribute to set in RM
743 :param value: Value of attribute to set in RM
746 :param guids1: List of guids of RMs subjected to action
749 :param action: Action to register (either START or STOP)
750 :type action: ResourceAction
752 :param guids2: List of guids of RMs to we waited for
755 :param state: State to wait for on RMs (STARTED, STOPPED, etc)
756 :type state: ResourceState
758 :param time: Time to wait after guids2 has reached status
762 if isinstance(guids1, int):
764 if isinstance(guids2, int):
768 rm = self.get_resource(guid)
769 rm.set_with_conditions(name, value, guids2, state, time)
771 def deploy(self, guids = None, wait_all_ready = True, group = None):
772 """ Deploys all ResourceManagers in the guids list.
774 If the argument 'guids' is not given, all RMs with state NEW
777 :param guids: List of guids of RMs to deploy
780 :param wait_all_ready: Wait until all RMs are ready in
781 order to start the RMs
784 :param group: Id of deployment group in which to deploy RMs
788 self.logger.debug(" ------- DEPLOY START ------ ")
791 # If no guids list was passed, all 'NEW' RMs will be deployed
793 for guid in self.resources:
794 if self.state(guid) == ResourceState.NEW:
797 if isinstance(guids, int):
800 # Create deployment group
801 # New guids can be added to a same deployment group later on
805 group = self._group_id_generator.next()
807 if group not in self._groups:
808 self._groups[group] = []
810 self._groups[group].extend(guids)
812 def wait_all_and_start(group):
813 # Function that checks if all resources are READY
814 # before scheduling a start_with_conditions for each RM
817 # Get all guids in group
818 guids = self._groups[group]
821 if self.state(guid) < ResourceState.READY:
826 callback = functools.partial(wait_all_and_start, group)
827 self.schedule("1s", callback)
829 # If all resources are ready, we schedule the start
831 rm = self.get_resource(guid)
832 self.schedule("0s", rm.start_with_conditions)
834 if rm.conditions.get(ResourceAction.STOP):
835 # Only if the RM has STOP conditions we
836 # schedule a stop. Otherwise the RM will stop immediately
837 self.schedule("0s", rm.stop_with_conditions)
839 if wait_all_ready and new_group:
840 # Schedule a function to check that all resources are
841 # READY, and only then schedule the start.
842 # This aims at reducing the number of tasks looping in the
844 # Instead of having many start tasks, we will have only one for
846 callback = functools.partial(wait_all_and_start, group)
847 self.schedule("0s", callback)
850 rm = self.get_resource(guid)
851 rm.deployment_group = group
852 self.schedule("0s", rm.deploy_with_conditions)
854 if not wait_all_ready:
855 self.schedule("0s", rm.start_with_conditions)
857 if rm.conditions.get(ResourceAction.STOP):
858 # Only if the RM has STOP conditions we
859 # schedule a stop. Otherwise the RM will stop immediately
860 self.schedule("0s", rm.stop_with_conditions)
862 def release(self, guids = None):
863 """ Releases all ResourceManagers in the guids list.
865 If the argument 'guids' is not given, all RMs registered
866 in the experiment are released.
868 :param guids: List of RM guids
872 if isinstance(guids, int):
876 guids = self.resources
879 rm = self.get_resource(guid)
880 self.schedule("0s", rm.release)
882 self.wait_released(guids)
885 if self.get(guid, "hardRelease"):
886 self.remove_resource(guid)
889 """ Releases all resources and stops the ExperimentController
892 # If there was a major failure we can't exit gracefully
893 if self._state == ECState.FAILED:
894 raise RuntimeError("EC failure. Can not exit gracefully")
896 # Remove all pending tasks from the scheduler queue
897 for tid in list(self._scheduler.pending):
898 self._scheduler.remove(tid)
900 # Remove pending tasks from the workers queue
905 # Mark the EC state as TERMINATED
906 self._state = ECState.TERMINATED
908 # Stop processing thread
911 # Notify condition to wake up the processing thread
914 if self._thread.is_alive():
917 def schedule(self, date, callback, track = False):
918 """ Schedules a callback to be executed at time 'date'.
920 :param date: string containing execution time for the task.
921 It can be expressed as an absolute time, using
922 timestamp format, or as a relative time matching
923 ^\d+.\d+(h|m|s|ms|us)$
925 :param callback: code to be executed for the task. Must be a
926 Python function, and receives args and kwargs
929 :param track: if set to True, the task will be retrievable with
930 the get_task() method
932 :return : The Id of the task
936 timestamp = stabsformat(date)
937 task = Task(timestamp, callback)
938 task = self._scheduler.schedule(task)
941 self._tasks[task.id] = task
943 # Notify condition to wake up the processing thread
949 """ Process scheduled tasks.
953 Tasks are scheduled by invoking the schedule method with a target
954 callback and an execution time.
955 The schedule method creates a new Task object with that callback
956 and execution time, and pushes it into the '_scheduler' queue.
957 The execution time and the order of arrival of tasks are used
958 to order the tasks in the queue.
960 The _process method is executed in an independent thread held by
961 the ExperimentController for as long as the experiment is running.
962 This method takes tasks from the '_scheduler' queue in a loop
963 and processes them in parallel using multithreading.
964 The environmental variable NEPI_NTHREADS can be used to control
965 the number of threads used to process tasks. The default value is
968 To execute tasks in parallel, a ParallelRunner (PR) object is used.
969 This object keeps a pool of threads (workers), and a queue of tasks
970 scheduled for 'immediate' execution.
972 On each iteration, the '_process' loop will take the next task that
973 is scheduled for 'future' execution from the '_scheduler' queue,
974 and if the execution time of that task is >= to the current time,
975 it will push that task into the PR for 'immediate execution'.
976 As soon as a worker is free, the PR will assign the next task to
979 Upon receiving a task to execute, each PR worker (thread) will
980 invoke the _execute method of the EC, passing the task as
982 The _execute method will then invoke task.callback inside a
983 try/except block. If an exception is raised by the tasks.callback,
984 it will be trapped by the try block, logged to standard error
985 (usually the console), and the task will be marked as failed.
991 while not self._stop:
995 task = self._scheduler.next()
998 # No task to execute. Wait for a new task to be scheduled.
1001 # The task timestamp is in the future. Wait for timeout
1002 # or until another task is scheduled.
1004 if now < task.timestamp:
1005 # Calculate timeout in seconds
1006 timeout = tdiffsec(task.timestamp, now)
1008 # Re-schedule task with the same timestamp
1009 self._scheduler.schedule(task)
1013 # Wait timeout or until a new task awakes the condition
1014 self._cond.wait(timeout)
1016 self._cond.release()
1019 # Process tasks in parallel
1020 self._runner.put(self._execute, task)
1023 err = traceback.format_exc()
1024 self.logger.error("Error while processing tasks in the EC: %s" % err)
1026 # Set the EC to FAILED state
1027 self._state = ECState.FAILED
1029 # Set the FailureManager failure level to EC failure
1030 self._fm.set_ec_failure()
1032 self.logger.debug("Exiting the task processing loop ... ")
1035 self._runner.destroy()
1037 def _execute(self, task):
1038 """ Executes a single task.
1040 :param task: Object containing the callback to execute
1046 task.result = task.callback()
1047 task.status = TaskStatus.DONE
1050 err = traceback.format_exc()
1052 task.status = TaskStatus.ERROR
1054 self.logger.error("Error occurred while executing task: %s" % err)
1057 """ Awakes the processing thread if it is blocked waiting
1058 for new tasks to arrive
1061 self._cond.acquire()
1063 self._cond.release()