Exemplo n.º 1
0
    def start(self, setup=None):
        self._setup = setup
        if setup is None:
            return self._start_master()
        self.log.info('%s poller starting', setup)

        if setup == '[dummy]':
            return

        try:
            session.loadSetup(setup, allow_startupcode=False)
            for devname in session.getSetupInfo()[setup]['devices']:
                if devname in self.blacklist:
                    self.log.debug('not polling %s, it is blacklisted',
                                   devname)
                    continue
                # import the device class in the main thread; this is necessary
                # for some external modules like Epics
                self.log.debug('importing device class for %s', devname)
                try:
                    session.importDevice(devname)
                except Exception:
                    self.log.warning(
                        '%-10s: error importing device class, '
                        'not retrying this device',
                        devname,
                        exc=True)
                    continue
                self.log.debug('starting thread for %s', devname)
                queue = Queue.Queue()
                worker = createThread('%s poller' % devname,
                                      self._worker_thread,
                                      args=(devname, queue))
                worker.queue = queue
                self._workers[devname.lower()] = worker
                # start staggered to not poll all devs at once....
                # use just a small delay, exact value does not matter
                sleep(0.0719)
            session.cache.addPrefixCallback('poller', self.enqueue_params_poll)

        except ConfigurationError as err:
            self.log.warning('Setup %r has failed to load!', setup)
            self.log.error(err, exc=True)
            self.log.warning('Not polling any devices!')

        # start a thread checking for modification of the setup file
        createThread('refresh checker', self._checker, args=(setup, ))
        self.log.info('%s poller startup complete', setup)
Exemplo n.º 2
0
def session(request):
    """Test session fixture"""

    nicos_session.__class__ = TestSession
    nicos_session.__init__(request.module.__name__)
    # override the sessionid: test module, and a finer resolved timestamp
    nicos_session.sessionid = '%s-%s' % (request.module.__name__, time.time())
    nicos_session.setMode(getattr(request.module, 'session_mode', MASTER))
    if request.module.session_setup:
        nicos_session.unloadSetup()
        nicos_session.loadSetup(
            request.module.session_setup,
            **getattr(request.module, 'session_load_kw', {}))
    if getattr(request.module, 'session_spmode', False):
        nicos_session.setSPMode(True)
    yield nicos_session
    nicos_session.setSPMode(False)
    nicos_session.shutdown()
Exemplo n.º 3
0
def NewSetup(*setupnames):
    """Load the given setups instead of the current one.

    Example:

    >>> NewSetup('tas', 'psd')

    will clear the current setup and load the "tas" and "psd" setups at the
    same time.

    Without arguments, the current setups are reloaded.  Example:

    >>> NewSetup()

    You can use `ListSetups()` to find out which setups are available.

    see also: `AddSetup`, `RemoveSetup`, `ListSetups`
    """
    current_mode = session.mode
    # reload current setups if none given
    update_aliases = True
    if not setupnames:
        update_aliases = False
        setupnames = session.explicit_setups
    # refresh setup files first
    session.readSetups()
    session.checkSetupCompatibility(setupnames, set())
    session.unloadSetup()
    try:
        session.startMultiCreate()
        try:
            session.loadSetup(setupnames, update_aliases=update_aliases)
        finally:
            session.endMultiCreate()
    except Exception:
        session.log.warning(
            'could not load new setup, falling back to '
            'startup setup',
            exc=1)
        session.unloadSetup()
        session.loadSetup('startup')
    if current_mode == MASTER:
        # need to refresh master status
        session.setMode(MASTER)
Exemplo n.º 4
0
def AddSetup(*setupnames):
    """Load the given setups additional to the current one.

    Example:

    >>> AddSetup('gaussmeter')

    will load the "gaussmeter" setup in addition to the current setups.

    You can use `ListSetups()` to find out which setups are available.

    see also: `NewSetup`, `RemoveSetup`, `ListSetups`
    """
    if not setupnames:
        ListSetups()
        return
    session.readSetups()
    session.checkSetupCompatibility(setupnames, session.loaded_setups)
    session.startMultiCreate()
    try:
        session.loadSetup(setupnames)
    finally:
        session.endMultiCreate()
Exemplo n.º 5
0
 def _get_maindev(cls, appname, maindevname, setupname):
     session.loadSetup(setupname or appname, allow_special=True,
                       raise_failed=True, autoload_system=False)
     return session.getDevice(maindevname or appname.capitalize())
Exemplo n.º 6
0
    def run(cls, sock, uuid, setups, user, code, quiet=False, debug=False):
        session.__class__ = cls
        session._is_sandboxed = sock.startswith('ipc://')
        session._debug_log = debug

        socket = nicos_zmq_ctx.socket(zmq.DEALER)
        socket.connect(sock)

        # we either get an empty message (retrieve cache data ourselves)
        # or a pickled key-value database
        data = socket.recv()
        db = pickle.loads(data) if data else None

        # send log messages back to daemon if requested
        session.log_sender = SimLogSender(socket, session, uuid, quiet)

        username, level = user.rsplit(',', 1)
        session._user = User(username, int(level))

        try:
            session.__init__(SIMULATION)
        except Exception as err:
            try:
                session.log.exception('Fatal error while initializing')
            finally:
                print('Fatal error while initializing:', err, file=sys.stderr)
            return 1

        # Give a sign of life and then tell the log handler to only log
        # errors during setup.
        session.log.info('setting up dry run...')
        session.begin_setup()
        # Handle "print" statements in the script.
        sys.stdout = LoggingStdout(sys.stdout)

        try:
            # Initialize the session in simulation mode.
            session._mode = SIMULATION

            # Load the setups from the original system, this should give the
            # information about the cache address.
            session.log.info('loading simulation mode setups: %s',
                             ', '.join(setups))
            session.loadSetup(setups, allow_startupcode=False)

            # Synchronize setups and cache values.
            session.log.info('synchronizing to master session')
            session.simulationSync(db)

            # Set session to always abort on errors.
            session.experiment.errorbehavior = 'abort'
        except:  # really *all* exceptions -- pylint: disable=W0702
            session.log.exception('Exception in dry run setup')
            session.log_sender.finish()
            session.shutdown()
            return 1

        # Set up log handlers to output everything.
        session.log_sender.begin_exec()
        # Execute the script code.
        exception = False
        try:
            last_clock = session.clock.time
            code, _ = parseScript(code)
            for i, c in enumerate(code):
                exec_(c, session.namespace)
                time = session.clock.time - last_clock
                last_clock = session.clock.time
                session.log_sender.send_block_result(i, time)
        except Abort:
            session.log.info('Dry run finished by abort()')
        except:  # pylint: disable=W0702
            session.log.exception('Exception in dry run')
            exception = True
        else:
            session.log.info('Dry run finished')
        finally:
            session.log_sender.finish(exception)

        # Shut down.
        session.shutdown()