Source code for sardana.tango.macroserver.test.macroexecutor

#!/usr/bin/env python

##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
##
# Sardana is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
##
# You should have received a copy of the GNU Lesser General Public License
# along with Sardana.  If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################

import atexit
import copy
import threading
import time

import PyTango
from taurus.core.util.codecs import CodecFactory

from sardana import sardanacustomsettings
from sardana.macroserver.macros.test import BaseMacroExecutor


[docs] class TangoAttrCb(object): """An abstract callback class for Tango events""" def __init__(self, tango_macro_executor): self._tango_macro_executor = tango_macro_executor
[docs] class TangoResultCb(TangoAttrCb): """Callback class for Tango events of the Result attribute"""
[docs] def push_event(self, *args, **kwargs): """callback method receiving the event""" event_data = args[0] if event_data.err: result = event_data.errors else: result = event_data.attr_value.value self._tango_macro_executor._result = result
[docs] class TangoLogCb(TangoAttrCb): """Callback class for Tango events of the log attributes e.g. Output, Error, Critical """ def __init__(self, tango_macro_executor, log_name): self._tango_macro_executor = tango_macro_executor self._log_name = log_name
[docs] def push_event(self, *args, **kwargs): """callback method receiving the event""" event_data = args[0] if event_data.attr_value: log = event_data.attr_value.value log_buffer_name = "_%s" % self._log_name log_buffer = getattr(self._tango_macro_executor, log_buffer_name) log_buffer.append(log) common_buffer = self._tango_macro_executor._common if common_buffer is not None: common_buffer.append(log)
[docs] class TangoStatusCb(TangoAttrCb): """Callback class for Tango events of the MacroStatus attribute""" START_STATES = ["start"] DONE_STATES = ["finish", "stop", "exception"]
[docs] def push_event(self, *args, **kwargs): """callback method receiving the event""" event_data = args[0] if event_data.err: # record the failure on the executor (getStateBuffer and # getExceptionStr read it from there), appending before # setting the event so a woken waiter always sees it self._tango_macro_executor._exception = str(event_data.errors) self._tango_macro_executor._state_buffer.append("exception") self._tango_macro_executor._done_event.set() return attr_value = getattr(event_data, "attr_value") if attr_value is None: return v = attr_value.value if not len(v[1]): return fmt = v[0] codec = CodecFactory().getCodec(fmt) fmt, data = codec.decode(v) executed_macro = getattr(self._tango_macro_executor, "_macro_name", None) for macro_status in data: state = macro_status["state"] exc_stack = macro_status.get("exc_stack") if state == "exception": exception_str = "" for line in exc_stack: exception_str += line self._tango_macro_executor._exception = exception_str # append to the buffer before setting the events, so a # waiter woken by the event always sees the terminal state self._tango_macro_executor._state_buffer.append(state) # only the executed macro's states control the events - # macros executing other macros (e.g. runMacro) emit status # events for the inner macros too, and an inner "finish" # must not end the wait name = macro_status.get("name") if None not in (name, executed_macro) and name != executed_macro: continue if state in self.START_STATES: self._tango_macro_executor._started_event.set() elif state in self.DONE_STATES: self._tango_macro_executor._done_event.set()
[docs] class TangoMacroExecutor(BaseMacroExecutor): """ Macro executor implemented using Tango communication with the Door device """ _api_util_cleanup_registered = False def __init__(self, door_name=None): super(TangoMacroExecutor, self).__init__() if door_name is None: door_name = getattr(sardanacustomsettings, "UNITTEST_DOOR_NAME") self._door = PyTango.DeviceProxy(door_name) # RunMacro/StopMacro can exceed the default 3 s client timeout # on loaded machines self._door.set_timeout_millis(15000) self._done_event = None self._started_event = None self._status_id = None self._macro_name = None if not TangoMacroExecutor._api_util_cleanup_registered: # remove whenever PyTango#390 gets fixed atexit.register(PyTango.ApiUtil.cleanup) TangoMacroExecutor._api_util_cleanup_registered = True def _clean(self): """Recreates threading Events in case the macro executor is reused.""" super(TangoMacroExecutor, self)._clean() self._started_event = threading.Event() self._done_event = threading.Event() def _run(self, macro_name, macro_params): """reimplemented from :class:`BaseMacroExecutor`""" # preaparing RunMacro command input arguments argin = copy.copy(macro_params) argin.insert(0, macro_name) self._macro_name = macro_name # registering for MacroStatus events status_cb = TangoStatusCb(self) self._status_id = self._door.subscribe_event( "macrostatus", PyTango.EventType.CHANGE_EVENT, status_cb ) # executing RunMacro command try: self._door.RunMacro(argin) except Exception: # do not leak the event subscription when the macro could # not even be started self._unsubscribe_status() raise def _unsubscribe_status(self): if self._status_id is not None: try: self._door.unsubscribe_event(self._status_id) finally: self._status_id = None def _wait(self, timeout): """reimplemented from :class:`BaseMacroExecutor`""" if not self._done_event: return try: done = self._done_event.wait(timeout) if not done: # stop the overrunning macro so the shared Door stays # usable for the following tests, then report the # timeout try: self._door.StopMacro() self._done_event.wait(10) self._wait_door_not_running(10) except PyTango.DevFailed: pass raise TimeoutError( "macro {} did not finish within {} s; state buffer: {}".format( getattr(self, "_macro_name", "?"), timeout, self._state_buffer, ) ) # the done status event is emitted before the Door device # leaves the RUNNING state; wait (bounded) until it does, # otherwise the next RunMacro fails with "not allowed when # the device is in RUNNING state" on slow or loaded machines if not self._wait_door_not_running(30): raise RuntimeError( "Door {} still RUNNING 30 s after the macro reported done".format( self._door.name() ) ) finally: self._unsubscribe_status() def _wait_door_not_running(self, timeout): """Poll (bounded) until the Door device leaves the RUNNING state. Returns True when it did and False when it remains RUNNING until timeout. A communication failure is retried until the deadline and then propagated.""" deadline = time.monotonic() + timeout while True: try: state = self._door.state() except PyTango.DevFailed: if time.monotonic() >= deadline: raise else: if state != PyTango.DevState.RUNNING: return True if time.monotonic() >= deadline: return False time.sleep(0.1) def _stop(self, started_event_timeout=3.0): """reimplemented from :class:`BaseMacroExecutor`""" self._started_event.wait(started_event_timeout) try: self._door.StopMacro() except PyTango.DevFailed as e: raise Exception("Unable to Stop macro: %s" % e) def _registerLog(self, log_level): """reimplemented from :class:`BaseMacroExecutor`""" log_cb = TangoLogCb(self, log_level) id_log_name = "_%s_id" % log_level id_log = self._door.subscribe_event( log_level, PyTango.EventType.CHANGE_EVENT, log_cb ) setattr(self, id_log_name, id_log) def _unregisterLog(self, log_level): """reimplemented from :class:`BaseMacroExecutor`""" id_log_name = "_%s_id" % log_level id_log = getattr(self, id_log_name) self._door.unsubscribe_event(id_log) def _registerResult(self): """reimplemented from :class:`BaseMacroExecutor`""" result_cb = TangoResultCb(self) self._result_id = self._door.subscribe_event( "result", PyTango.EventType.CHANGE_EVENT, result_cb ) def _unregisterResult(self): """reimplemented from :class:`BaseMacroExecutor`""" self._door.unsubscribe_event(self._result_id)
[docs] def getData(self): """Returns the data object for the last executed macro :return: (obj) """ data = self._door.RecordData return CodecFactory().decode(data)