def run_tango_server(tango_util=None, start_time=None): try: if tango_util is None: tango_util = Util(sys.argv) util = Util.instance() SardanaServer.server_state = State.Init util.server_init() SardanaServer.server_state = State.Running if start_time is not None: import datetime dt = datetime.datetime.now() - start_time taurus.info("Ready to accept request in %s", dt) else: taurus.info("Ready to accept request") util.server_run() SardanaServer.server_state = State.Off taurus.info("Exiting") except DevFailed: taurus.info("Exiting") taurus.critical("Server exited with DevFailed", exc_info=1) except KeyboardInterrupt: taurus.info("Exiting") taurus.critical("Interrupted by keyboard") except Exception: taurus.info("Exiting") taurus.critical("Server exited with unforeseen exception", exc_info=1) taurus.info("Exited")
def run_tango_server(tango_util=None, start_time=None): # Import here to avoid circular import from sardana.tango.core.SardanaDevice import SardanaDevice try: if tango_util is None: tango_util = Util(sys.argv) util = Util.instance() SardanaServer.server_state = State.Init util.server_init() for device in util.get_device_list("*"): if isinstance(device, SardanaDevice): device.sardana_init_hook() SardanaServer.server_state = State.Running if start_time is not None: import datetime dt = datetime.datetime.now() - start_time taurus.info("Ready to accept request in %s", dt) else: taurus.info("Ready to accept request") util.server_run() SardanaServer.server_state = State.Off taurus.info("Exiting") except DevFailed: taurus.info("Exiting") taurus.critical("Server exited with DevFailed", exc_info=1) except KeyboardInterrupt: taurus.info("Exiting") taurus.critical("Interrupted by keyboard") except Exception: taurus.info("Exiting") taurus.critical("Server exited with unforeseen exception", exc_info=1) taurus.info("Exited")
def run(args=None): try: if not args: args = sys.argv[1:] args = [SERVER_NAME] + list(args) print 'running server with args: %s' % repr(args) util = Util(args) util.add_class(WebTornadoDS, WebTornadoDS4Impl) U = Util.instance() U.server_init() U.server_run() except DevFailed, e: print '-------> Received a DevFailed exception:', e
def _calculate_name(self, name): if name is None: return None util = Util.instance() return name % {'ds_name': util.get_ds_name().lower(), 'ds_exec_name': util.get_ds_exec_name(), 'ds_inst_name': util.get_ds_inst_name().lower()}
def init_device(self): SardanaDevice.init_device(self) self.set_change_event('State', True, False) self.set_change_event('Status', True, False) self.set_change_event('TypeList', True, False) self.set_change_event('DoorList', True, False) self.set_change_event('MacroList', True, False) self.set_change_event('MacroLibList', True, False) self.set_change_event('Elements', True, False) self.set_change_event('Environment', True, False) dev_class = self.get_device_class() self.get_device_properties(dev_class) self.EnvironmentDb = self._calculate_name(self.EnvironmentDb) self.LogReportFilename = self._calculate_name(self.LogReportFilename) macro_server = self.macro_server macro_server.set_python_path(self.PythonPath) macro_server.set_max_parallel_macros(self.MaxParallelMacros) # if it is not possible to store/retrieve the environment from the # current path then setup a new unique path and store the environment # there forever try: macro_server.set_environment_db(self.EnvironmentDb) except: self.error("Failed to set environment DB to %s", self.EnvironmentDb) self.debug("Details:", exc_info=1) import tempfile env_db = os.path.join(tempfile.mkdtemp(), MacroServerClass.DefaultEnvRelDir) env_db = self._calculate_name(env_db) db = Util.instance().get_database() db.put_device_property(self.get_name(), dict(EnvironmentDb=env_db)) self.EnvironmentDb = env_db macro_server.set_environment_db(self.EnvironmentDb) try: macro_server.set_log_report( self.LogReportFilename, self.LogReportFormat) except: self.error("Failed to setup log report to %s", self.LogReportFilename) self.debug("Details:", exc_info=1) macro_server.set_recorder_path(self.RecorderPath) macro_server.set_macro_path(self.MacroPath) macro_server.set_pool_names(self.PoolNames) if self.RConsolePort: try: import rfoo.utils.rconsole rfoo.utils.rconsole.spawn_server(port=self.RConsolePort) except Exception: self.warning("Failed to start rconsole") self.debug("Details:", exc_info=1) self.set_state(DevState.ON)
def init_device(self): SardanaDevice.init_device(self) self.set_change_event('State', True, False) self.set_change_event('Status', True, False) self.set_change_event('TypeList', True, False) self.set_change_event('DoorList', True, False) self.set_change_event('MacroList', True, False) self.set_change_event('MacroLibList', True, False) self.set_change_event('Elements', True, False) self.set_change_event('Environment', True, False) dev_class = self.get_device_class() self.get_device_properties(dev_class) self.EnvironmentDb = self._calculate_name(self.EnvironmentDb) self.LogReportFilename = self._calculate_name(self.LogReportFilename) macro_server = self.macro_server macro_server.set_python_path(self.PythonPath) macro_server.set_max_parallel_macros(self.MaxParallelMacros) # if it is not possible to store/retrieve the environment from the # current path then setup a new unique path and store the environment # there forever try: macro_server.set_environment_db(self.EnvironmentDb) except: self.error("Failed to set environment DB to %s", self.EnvironmentDb) self.debug("Details:", exc_info=1) import tempfile env_db = os.path.join(tempfile.mkdtemp(), MacroServerClass.DefaultEnvRelDir) env_db = self._calculate_name(env_db) db = Util.instance().get_database() db.put_device_property(self.get_name(), dict(EnvironmentDb=env_db)) self.EnvironmentDb = env_db macro_server.set_environment_db(self.EnvironmentDb) try: macro_server.set_log_report(self.LogReportFilename, self.LogReportFormat) except: self.error("Failed to setup log report to %s", self.LogReportFilename) self.debug("Details:", exc_info=1) macro_server.set_recorder_path(self.RecorderPath) macro_server.set_macro_path(self.MacroPath) macro_server.set_pool_names(self.PoolNames) if self.RConsolePort: try: import rfoo.utils.rconsole rfoo.utils.rconsole.spawn_server(port=self.RConsolePort) except Exception: self.warning("Failed to start rconsole") self.debug("Details:", exc_info=1) self.set_state(DevState.ON)
def init(self, name): SardanaDevice.init(self, name) if self._alias is None: self._alias = Util.instance().get_ds_inst_name() self._macro_server = ms = MS(self.get_full_name(), self.alias) ms.add_listener(self.on_macro_server_changed)
def write_Configuration(self, attr): data = attr.get_write_value() cfg = CodecFactory().decode(('json', data)) util = Util.instance() if util.is_svr_starting(): self.measurement_group._config._value_ref_compat = True else: self.measurement_group._config._value_ref_compat = False self.measurement_group.set_configuration_from_user(cfg)
def init(self, name): """initialize the device once in the object lifetime. Override when necessary but **always** call the method from your super class :param str name: device name""" SardanaDevice.init(self, name) util = Util.instance() self._pool_device = util.get_device_list_by_class("Pool")[0] self._element = None
def init_device(self): SardanaDevice.init_device(self) levels = 'Critical', 'Error', 'Warning', 'Info', 'Output', 'Debug' detect_evts = () non_detect_evts = [ 'State', 'Status', 'Result', 'RecordData', 'MacroStatus', 'Input' ] + list(levels) self.set_change_events(detect_evts, non_detect_evts) util = Util.instance() db = util.get_database() # Find the macro server for this door macro_servers = util.get_device_list_by_class("MacroServer") if self.MacroServerName is None: self._macro_server_device = macro_servers[0] else: ms_name = self.MacroServerName.lower() for ms in macro_servers: if ms.get_name().lower() == ms_name or \ ms.alias.lower() == ms_name: self._macro_server_device = ms break # support for old doors which didn't have ID if self.Id == InvalidId: self.Id = self.macro_server_device.macro_server.get_new_id() db.put_device_property(self.get_name(), dict(Id=self.Id)) door = self.door if door is None: full_name = self.get_name() name = full_name macro_server = self.macro_server_device.macro_server self.door = door = \ macro_server.create_element(type="Door", name=name, full_name=full_name, id=self.Id) self._setupLogHandlers(levels) multi_attr = self.get_device_attr() input_attr = multi_attr.get_attr_by_name('Input') self._input_handler = ih = TangoInputHandler(self, input_attr) door.set_input_handler(ih) recorddata_attr = multi_attr.get_attr_by_name('RecordData') self._pylab_handler = pylabh = TangoPylabHandler(self, recorddata_attr) door.set_pylab_handler(pylabh) self._pyplot_handler = pyploth = TangoPyplotHandler( self, recorddata_attr) door.set_pyplot_handler(pyploth) door.add_listener(self.on_door_changed) self.set_state(DevState.ON)
def init_device(self): SardanaDevice.init_device(self) levels = 'Critical', 'Error', 'Warning', 'Info', 'Output', 'Debug' detect_evts = () non_detect_evts = ['State', 'Status', 'Result', 'RecordData', 'MacroStatus', 'Input'] + list(levels) self.set_change_events(detect_evts, non_detect_evts) util = Util.instance() db = util.get_database() # Find the macro server for this door macro_servers = util.get_device_list_by_class("MacroServer") if self.MacroServerName is None: self._macro_server_device = macro_servers[0] else: ms_name = self.MacroServerName.lower() for ms in macro_servers: if ms.get_name().lower() == ms_name or \ ms.alias.lower() == ms_name: self._macro_server_device = ms break # support for old doors which didn't have ID if self.Id == InvalidId: self.Id = self.macro_server_device.macro_server.get_new_id() db.put_device_property(self.get_name(), dict(Id=self.Id)) door = self.door if door is None: full_name = self.get_name() name = full_name macro_server = self.macro_server_device.macro_server self.door = door = \ macro_server.create_element(type="Door", name=name, full_name=full_name, id=self.Id) self._setupLogHandlers(levels) multi_attr = self.get_device_attr() input_attr = multi_attr.get_attr_by_name('Input') self._input_handler = ih = TangoInputHandler(self, input_attr) door.set_input_handler(ih) recorddata_attr = multi_attr.get_attr_by_name('RecordData') self._pylab_handler = pylabh = TangoPylabHandler(self, recorddata_attr) door.set_pylab_handler(pylabh) self._pyplot_handler = pyploth = TangoPyplotHandler( self, recorddata_attr) door.set_pyplot_handler(pyploth) door.add_listener(self.on_door_changed) self.set_state(DevState.ON)
def get_role_ids(self): db = Util.instance().get_database() if db is None: return [] role_ids = db.get_device_property(self.get_name(), ["motor_role_ids"])["motor_role_ids"] if len(role_ids) == 0: role_ids = db.get_device_property(self.get_name(), ["counter_role_ids"])["counter_role_ids"] if len(role_ids) == 0: role_ids = self.Role_ids role_ids = map(int, role_ids) return role_ids
def _get_ctrl_properties(self): try: ctrl_info = self.pool.get_controller_class_info(self.Klass) prop_infos = ctrl_info.ctrl_properties except: return {} db = Util.instance().get_database() if db is None: return {} props = {} if prop_infos: props.update( db.get_device_property(self.get_name(), list(prop_infos.keys()))) for p in list(props.keys()): if len(props[p]) == 0: props[p] = None ret = {} missing_props = [] for prop_name, prop_value in list(props.items()): if prop_value is None: dv = prop_infos[prop_name].default_value if dv is None: missing_props.append(prop_name) ret[prop_name] = dv continue prop_info = prop_infos[prop_name] dtype, dformat = prop_info.dtype, prop_info.dformat op = str if dtype == DataType.Integer: op = int elif dtype == DataType.Double: op = float elif dtype == DataType.Boolean: op = to_bool prop_value = list(map(op, prop_value)) if dformat == DataFormat.Scalar: prop_value = prop_value[0] ret[prop_name] = prop_value if missing_props: self.set_state(DevState.ALARM) missing_props = ", ".join(missing_props) self.set_status("Controller has missing properties: %s" % missing_props) return ret
def _get_ctrl_properties(self): try: ctrl_info = self.pool.get_controller_class_info(self.Klass) prop_infos = ctrl_info.ctrl_properties except: return {} db = Util.instance().get_database() if db is None: return {} props = {} if prop_infos: props.update(db.get_device_property( self.get_name(), prop_infos.keys())) for p in props.keys(): if len(props[p]) == 0: props[p] = None ret = {} missing_props = [] for prop_name, prop_value in props.items(): if prop_value is None: dv = prop_infos[prop_name].default_value if dv is None: missing_props.append(prop_name) ret[prop_name] = dv continue prop_info = prop_infos[prop_name] dtype, dformat = prop_info.dtype, prop_info.dformat op = str if dtype == DataType.Integer: op = int elif dtype == DataType.Double: op = float elif dtype == DataType.Boolean: op = to_bool prop_value = map(op, prop_value) if dformat == DataFormat.Scalar: prop_value = prop_value[0] ret[prop_name] = prop_value if missing_props: self.set_state(DevState.ALARM) missing_props = ", ".join(missing_props) self.set_status("Controller has missing properties: %s" % missing_props) return ret
def get_role_ids(self): db = Util.instance().get_database() if db is None: return [] role_ids = db.get_device_property(self.get_name(), ['motor_role_ids'])['motor_role_ids'] if len(role_ids) == 0: role_ids = db.get_device_property( self.get_name(), ['counter_role_ids'])['counter_role_ids'] if len(role_ids) == 0: role_ids = self.Role_ids role_ids = map(int, role_ids) return role_ids
def write_Instrument(self, attr): """Write the value of the ``Instrument`` tango attribute. Sets a new instrument full name or empty string if this element doesn't belong to any instrument. The instrument **must** have been previously created. :param attr: tango instrument attribute :type attr: :class:`~PyTango.Attribute`""" name = attr.get_write_value() instrument = None if name: instrument = self.pool.get_element(full_name=name) if instrument.get_type() != ElementType.Instrument: raise Exception("%s is not an instrument" % name) self.element.instrument = instrument db = Util.instance().get_database() db.put_device_property(self.get_name(), { "Instrument_id" : instrument.id })
def init_device(self): Device.init_device(self) self.device = None try: config = get_config() util = Util.instance() if not util.is_svr_starting(): config.reload() self.device = config.get(self.card_name) if isinstance(self.device, BaseCard): raise ValueError('ct2 card config is not supported anymore') switch_state(self, DevState.ON, "Ready!") except Exception as e: msg = "Exception initializing device: {0}".format(e) self.error_stream(msg) switch_state(self, DevState.FAULT, msg)
def write_Instrument(self, attr): """Write the value of the ``Instrument`` tango attribute. Sets a new instrument full name or empty string if this element doesn't belong to any instrument. The instrument **must** have been previously created. :param attr: tango instrument attribute :type attr: :class:`~PyTango.Attribute`""" name = attr.get_write_value() instrument = None if name: instrument = self.pool.get_element(full_name=name) if instrument.get_type() != ElementType.Instrument: raise Exception("%s is not an instrument" % name) self.element.instrument = instrument db = Util.instance().get_database() db.put_device_property(self.get_name(), {"Instrument_id": instrument.id})
def get_database(self): """Helper method to return a reference to the current tango database :return: the Tango database :rtype: :class:`~PyTango.Database`""" return Util.instance().get_database()
def terminate(self): if not self.is_alive(): return Util.instance().get_dserver_device().kill()
def run(prepare_func, args=None, tango_util=None, start_time=None, mode=None, name=None): if mode is None: mode = ServerRunMode.SynchPure if args is None: if mode != ServerRunMode.SynchPure: raise Exception("When running in separate thread/process, " "'args' must be given") args = sys.argv if name is None: name = args[0] else: args = [name] + list(args[1:]) if mode != ServerRunMode.SynchPure: if mode in (ServerRunMode.SynchThread, ServerRunMode.AsynchThread): import threading class task_klass(threading.Thread): def terminate(self): if not self.is_alive(): return Util.instance().get_dserver_device().kill() else: import multiprocessing task_klass = multiprocessing.Process tango_util = None task_args = prepare_func, task_kwargs = dict(args=args, tango_util=tango_util, start_time=start_time, mode=ServerRunMode.SynchPure) task = task_klass(name=name, target=run, args=task_args, kwargs=task_kwargs) task.daemon = False task.start() if mode in (ServerRunMode.SynchThread, ServerRunMode.SynchProcess): task.join() return task log_messages = [] try: options, args, tango_args, ORB_args = prepare_cmdline(args=args) except KeyboardInterrupt: pass log_messages.extend(prepare_environment(args, tango_args, ORB_args)) log_messages.extend(prepare_server(args, tango_args)) if tango_util is None: tango_util = Util(tango_args) prepare_func(tango_util) prepare_taurus(options, args, tango_args) prepare_logging(options, args, tango_args, start_time=start_time, log_messages=log_messages) prepare_rconsole(options, args, tango_args) run_tango_server(tango_util, start_time=start_time)
def get_spec_names(): util = Util.instance() tango_specs = util.get_device_list_by_class("Spec") if not tango_specs: return [] return [ts.Spec for ts in tango_specs]
options, args, tango_args, ORB_args = prepare_cmdline(args=args) except KeyboardInterrupt: pass log_messages.extend(prepare_environment(args, tango_args, ORB_args)) try: log_messages.extend(prepare_server(args, tango_args)) except AbortException, e: print e.message return except KeyboardInterrupt: print("\nInterrupted by keyboard") return log_messages.extend(prepare_logstash(args)) if tango_util is None: tango_util = Util(tango_args) prepare_func(tango_util) prepare_taurus(options, args, tango_args) prepare_logging(options, args, tango_args, start_time=start_time, log_messages=log_messages) prepare_rconsole(options, args, tango_args) run_tango_server(tango_util, start_time=start_time)
def get_restore_data(self): restore_attributes = self.get_attributes_to_restore() db = Util.instance().get_database() db_values = db.get_device_attribute_property(self.get_name(), restore_attributes) return restore_attributes, db_values