/usr/lib/python2.7/dist-packages/simpy/events.py is in python-simpy3 3.0.10-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 | """
This module contains the basic event types used in SimPy.
The base class for all events is :class:`Event`. Though it can be directly
used, there are several specialized subclasses of it.
.. autosummary::
~simpy.events.Event
~simpy.events.Timeout
~simpy.events.Process
~simpy.events.AnyOf
~simpy.events.AllOf
This module also defines the :exc:`Interrupt` exception.
"""
from simpy._compat import PY2
if PY2:
import sys
PENDING = object()
"""Unique object to identify pending values of events."""
URGENT = 0
"""Priority of interrupts and process initialization events."""
NORMAL = 1
"""Default priority used by events."""
class Event(object):
"""An event that may happen at some point in time.
An event
- may happen (:attr:`triggered` is ``False``),
- is going to happen (:attr:`triggered` is ``True``) or
- has happened (:attr:`processed` is ``True``).
Every event is bound to an environment *env* and is initially not
triggered. Events are scheduled for processing by the environment after
they are triggered by either :meth:`succeed`, :meth:`fail` or
:meth:`trigger`. These methods also set the *ok* flag and the *value* of
the event.
An event has a list of :attr:`callbacks`. A callback can be any callable.
Once an event gets processed, all callbacks will be invoked with the event
as the single argument. Callbacks can check if the event was successful by
examining *ok* and do further processing with the *value* it has produced.
Failed events are never silently ignored and will raise an exception upon
being processed. If a callback handles an exception, it must set :attr:`defused`
to ``True`` to prevent this.
This class also implements ``__and__()`` (``&``) and ``__or__()`` (``|``).
If you concatenate two events using one of these operators,
a :class:`Condition` event is generated that lets you wait for both or one
of them.
"""
def __init__(self, env):
self.env = env
"""The :class:`~simpy.core.Environment` the event lives in."""
self.callbacks = []
"""List of functions that are called when the event is processed."""
self._value = PENDING
def __repr__(self):
"""Return the description of the event (see :meth:`_desc`) with the id
of the event."""
return '<%s object at 0x%x>' % (self._desc(), id(self))
def _desc(self):
"""Return a string *Event()*."""
return '%s()' % self.__class__.__name__
@property
def triggered(self):
"""Becomes ``True`` if the event has been triggered and its callbacks
are about to be invoked."""
return self._value is not PENDING
@property
def processed(self):
"""Becomes ``True`` if the event has been processed (e.g., its
callbacks have been invoked)."""
return self.callbacks is None
@property
def ok(self):
"""Becomes ``True`` when the event has been triggered successfully.
A "successful" event is one triggered with :meth:`succeed()`.
:raises AttributeError: if accessed before the event is triggered.
"""
return self._ok
@property
def defused(self):
"""Becomes ``True`` when the failed event's exception is "defused".
When an event fails (i.e. with :meth:`fail()`), the failed event's
`value` is an exception that will be re-raised when the
:class:`~simpy.core.Environment` processes the event (i.e. in
:meth:`~simpy.core.Environment.step()`).
It is also possible for the failed event's exception to be defused by
setting :attr:`defused` to ``True`` from an event callback. Doing so
prevents the event's exception from being re-raised when the event is
processed by the :class:`~simpy.core.Environment`.
"""
return hasattr(self, '_defused')
@defused.setter
def defused(self, value):
self._defused = True
@property
def value(self):
"""The value of the event if it is available.
The value is available when the event has been triggered.
Raises :exc:`AttributeError` if the value is not yet available.
"""
if self._value is PENDING:
raise AttributeError('Value of %s is not yet available' % self)
return self._value
def trigger(self, event):
"""Trigger the event with the state and value of the provided *event*.
Return *self* (this event instance).
This method can be used directly as a callback function to trigger
chain reactions.
"""
self._ok = event._ok
self._value = event._value
self.env.schedule(self)
def succeed(self, value=None):
"""Set the event's value, mark it as successful and schedule it for
processing by the environment. Returns the event instance.
Raises :exc:`RuntimeError` if this event has already been triggerd.
"""
if self._value is not PENDING:
raise RuntimeError('%s has already been triggered' % self)
self._ok = True
self._value = value
self.env.schedule(self)
return self
def fail(self, exception):
"""Set *exception* as the events value, mark it as failed and schedule
it for processing by the environment. Returns the event instance.
Raises :exc:`ValueError` if *exception* is not an :exc:`Exception`.
Raises :exc:`RuntimeError` if this event has already been triggered.
"""
if self._value is not PENDING:
raise RuntimeError('%s has already been triggered' % self)
if not isinstance(exception, BaseException):
raise ValueError('%s is not an exception.' % exception)
self._ok = False
self._value = exception
self.env.schedule(self)
return self
def __and__(self, other):
"""Return a :class:`~simpy.events.Condition` that will be triggered if
both, this event and *other*, have been processed."""
return Condition(self.env, Condition.all_events, [self, other])
def __or__(self, other):
"""Return a :class:`~simpy.events.Condition` that will be triggered if
either this event or *other* have been processed (or even both, if they
happened concurrently)."""
return Condition(self.env, Condition.any_events, [self, other])
class Timeout(Event):
"""A :class:`~simpy.events.Event` that gets triggered after a *delay* has
passed.
This event is automatically triggered when it is created.
"""
def __init__(self, env, delay, value=None):
if delay < 0:
raise ValueError('Negative delay %s' % delay)
# NOTE: The following initialization code is inlined from
# Event.__init__() for performance reasons.
self.env = env
self.callbacks = []
self._value = value
self._delay = delay
self._ok = True
env.schedule(self, NORMAL, delay)
def _desc(self):
"""Return a string *Timeout(delay[, value=value])*."""
return '%s(%s%s)' % (self.__class__.__name__, self._delay,
'' if self._value is None else
(', value=%s' % self._value))
class Initialize(Event):
"""Initializes a process. Only used internally by :class:`Process`.
This event is automatically triggered when it is created.
"""
def __init__(self, env, process):
# NOTE: The following initialization code is inlined from
# Event.__init__() for performance reasons.
self.env = env
self.callbacks = [process._resume]
self._value = None
# The initialization events needs to be scheduled as urgent so that it
# will be handled before interrupts. Otherwise a process whose
# generator has not yet been started could be interrupted.
self._ok = True
env.schedule(self, URGENT)
class Interruption(Event):
"""Immediately schedules an :class:`Interrupt` exception with the given
*cause* to be thrown into *process*.
This event is automatically triggered when it is created.
"""
def __init__(self, process, cause):
# NOTE: The following initialization code is inlined from
# Event.__init__() for performance reasons.
self.env = process.env
self.callbacks = [self._interrupt]
self._value = Interrupt(cause)
self._ok = False
self._defused = True
if process._value is not PENDING:
raise RuntimeError('%s has terminated and cannot be interrupted.' %
process)
if process is self.env.active_process:
raise RuntimeError('A process is not allowed to interrupt itself.')
self.process = process
self.env.schedule(self, URGENT)
def _interrupt(self, event):
# Ignore dead processes. Multiple concurrently scheduled interrupts
# cause this situation. If the process dies while handling the first
# one, the remaining interrupts must be ignored.
if self.process._value is not PENDING:
return
# A process never expects an interrupt and is always waiting for a
# target event. Remove the process from the callbacks of the target.
self.process._target.callbacks.remove(self.process._resume)
self.process._resume(self)
class Process(Event):
"""Process an event yielding generator.
A generator (also known as a coroutine) can suspend its execution by
yielding an event. ``Process`` will take care of resuming the generator
with the value of that event once it has happened. The exception of failed
events is thrown into the generator.
``Process`` itself is an event, too. It is triggered, once the generator
returns or raises an exception. The value of the process is the return
value of the generator or the exception, respectively.
.. note::
Python version prior to 3.3 do not support return statements in
generators. You can use :meth:~simpy.core.Environment.exit() as
a workaround.
Processes can be interrupted during their execution by :meth:`interrupt`.
"""
def __init__(self, env, generator):
if not hasattr(generator, 'throw'):
# Implementation note: Python implementations differ in the
# generator types they provide. Cython adds its own generator type
# in addition to the CPython type, which renders a type check
# impractical. To workaround this issue, we check for attribute
# name instead of type and optimistically assume that all objects
# with a ``throw`` attribute are generators (the more intuitive
# name ``__next__`` cannot be used because it was renamed from
# ``next`` in Python 2).
# Remove this workaround if it causes issues in production!
raise ValueError('%s is not a generator.' % generator)
# NOTE: The following initialization code is inlined from
# Event.__init__() for performance reasons.
self.env = env
self.callbacks = []
self._value = PENDING
self._generator = generator
# Schedule the start of the execution of the process.
self._target = Initialize(env, self)
def _desc(self):
"""Return a string *Process(process_func_name)*."""
return '%s(%s)' % (self.__class__.__name__, self._generator.__name__)
@property
def target(self):
"""The event that the process is currently waiting for.
Returns ``None`` if the process is dead or it is currently being
interrupted.
"""
return self._target
@property
def is_alive(self):
"""``True`` until the process generator exits."""
return self._value is PENDING
def interrupt(self, cause=None):
"""Interupt this process optionally providing a *cause*.
A process cannot be interrupted if it already terminated. A process can
also not interrupt itself. Raise a :exc:`RuntimeError` in these
cases.
"""
Interruption(self, cause)
def _resume(self, event):
"""Resumes the execution of the process with the value of *event*. If
the process generator exits, the process itself will get triggered with
the return value or the exception of the generator."""
# Mark the current process as active.
self.env._active_proc = self
while True:
# Get next event from process
try:
if event._ok:
event = self._generator.send(event._value)
else:
# The process has no choice but to handle the failed event
# (or fail itself).
event._defused = True
# Create an exclusive copy of the exception for this
# process to prevent traceback modifications by other
# processes.
exc = type(event._value)(*event._value.args)
exc.__cause__ = event._value
if PY2:
if hasattr(event._value, '__traceback__'):
exc.__traceback__ = event._value.__traceback__
event = self._generator.throw(exc)
except StopIteration as e:
# Process has terminated.
event = None
self._ok = True
self._value = e.args[0] if len(e.args) else None
self.env.schedule(self)
break
except BaseException as e:
# Process has failed.
event = None
self._ok = False
tb = e.__traceback__ if not PY2 else sys.exc_info()[2]
# Strip the frame of this function from the traceback as it
# does not add any useful information.
e.__traceback__ = tb.tb_next
self._value = e
self.env.schedule(self)
break
# Process returned another event to wait upon.
try:
# Be optimistic and blindly access the callbacks attribute.
if event.callbacks is not None:
# The event has not yet been triggered. Register callback
# to resume the process if that happens.
event.callbacks.append(self._resume)
break
except AttributeError:
# Our optimism didn't work out, figure out what went wrong and
# inform the user.
if not hasattr(event, 'callbacks'):
msg = 'Invalid yield value "%s"' % event
descr = _describe_frame(self._generator.gi_frame)
error = RuntimeError('\n%s%s' % (descr, msg))
# Drop the AttributeError as the cause for this exception.
error.__cause__ = None
raise error
self._target = event
self.env._active_proc = None
class ConditionValue(object):
"""Result of a :class:`~simpy.events.Condition`. It supports convenient
dict-like access to the triggered events and their values. The events are
ordered by their occurences in the condition."""
def __init__(self):
self.events = []
def __getitem__(self, key):
if key not in self.events:
raise KeyError(str(key))
return key._value
def __contains__(self, key):
return key in self.events
def __eq__(self, other):
if type(other) is ConditionValue:
return self.events == other.events
return self.todict() == other
def __repr__(self):
return '<ConditionValue %s>' % self.todict()
def __iter__(self):
return self.keys()
def keys(self):
return (event for event in self.events)
def values(self):
return (event._value for event in self.events)
def items(self):
return ((event, event._value) for event in self.events)
def todict(self):
return dict((event, event._value) for event in self.events)
class Condition(Event):
"""An event that gets triggered once the condition function *evaluate*
returns ``True`` on the given list of *events*.
The value of the condition event is an instance of :class:`ConditionValue`
which allows convenient access to the input events and their values. The
:class:`ConditionValue` will only contain entries for those events that
occurred before the condition is processed.
If one of the events fails, the condition also fails and forwards the
exception of the failing event.
The *evaluate* function receives the list of target events and the number
of processed events in this list: ``evaluate(events, processed_count)``. If
it returns ``True``, the condition is triggered. The
:func:`Condition.all_events()` and :func:`Condition.any_events()` functions
are used to implement *and* (``&``) and *or* (``|``) for events.
Condition events can be nested.
"""
def __init__(self, env, evaluate, events):
super(Condition, self).__init__(env)
self._evaluate = evaluate
self._events = events if type(events) is tuple else tuple(events)
self._count = 0
if not self._events:
# Immediately succeed if no events are provided.
self.succeed(ConditionValue())
return
# Check if events belong to the same environment.
for event in self._events:
if self.env != event.env:
raise ValueError('It is not allowed to mix events from '
'different environments')
# Check if the condition is met for each processed event. Attach
# _check() as a callback otherwise.
for event in self._events:
if event.callbacks is None:
self._check(event)
else:
event.callbacks.append(self._check)
# Register a callback which will build the value of this condition
# after it has been triggered.
self.callbacks.append(self._build_value)
def _desc(self):
"""Return a string *Condition(evaluate, [events])*."""
return '%s(%s, %s)' % (self.__class__.__name__,
self._evaluate.__name__, self._events)
def _populate_value(self, value):
"""Populate the *value* by recursively visiting all nested
conditions."""
for event in self._events:
if isinstance(event, Condition):
event._populate_value(value)
elif event.callbacks is None:
value.events.append(event)
def _build_value(self, event):
"""Build the value of this condition."""
self._remove_check_callbacks()
if event._ok:
self._value = ConditionValue()
self._populate_value(self._value)
def _remove_check_callbacks(self):
"""Remove _check() callbacks from events recursively.
Once the condition has triggered, the condition's events no longer need
to have _check() callbacks. Removing the _check() callbacks is
important to break circular references between the condition and
untriggered events.
"""
for event in self._events:
if event.callbacks and self._check in event.callbacks:
event.callbacks.remove(self._check)
if isinstance(event, Condition):
event._remove_check_callbacks()
def _check(self, event):
"""Check if the condition was already met and schedule the *event* if
so."""
if self._value is not PENDING:
return
self._count += 1
if not event._ok:
# Abort if the event has failed.
event._defused = True
self.fail(event._value)
elif self._evaluate(self._events, self._count):
# The condition has been met. The _build_value() callback will
# populate the ConditionValue once this condition is processed.
self.succeed()
@staticmethod
def all_events(events, count):
"""An evaluation function that returns ``True`` if all *events* have
been triggered."""
return len(events) == count
@staticmethod
def any_events(events, count):
"""An evaluation function that returns ``True`` if at least one of
*events* has been triggered."""
return count > 0 or len(events) == 0
class AllOf(Condition):
"""A :class:`~simpy.events.Condition` event that is triggered if all of
a list of *events* have been successfully triggered. Fails immediately if
any of *events* failed.
"""
def __init__(self, env, events):
super(AllOf, self).__init__(env, Condition.all_events, events)
class AnyOf(Condition):
"""A :class:`~simpy.events.Condition` event that is triggered if any of
a list of *events* has been successfully triggered. Fails immediately if
any of *events* failed.
"""
def __init__(self, env, events):
super(AnyOf, self).__init__(env, Condition.any_events, events)
class Interrupt(Exception):
"""Exception thrown into a process if it is interrupted (see
:func:`~simpy.events.Process.interrupt()`).
:attr:`cause` provides the reason for the interrupt, if any.
If a process is interrupted concurrently, all interrupts will be thrown
into the process in the same order as they occurred.
"""
def __str__(self):
return '%s(%r)' % (self.__class__.__name__, self.cause)
@property
def cause(self):
"""The cause of the interrupt or ``None`` if no cause was provided."""
return self.args[0]
def _describe_frame(frame):
"""Print filename, line number and function name of a stack frame."""
filename, name = frame.f_code.co_filename, frame.f_code.co_name
lineno = frame.f_lineno
with open(filename) as f:
for no, line in enumerate(f):
if no + 1 == lineno:
break
return ' File "%s", line %d, in %s\n %s\n' % (filename, lineno, name,
line.strip())
|