Пример #1
0
def session(request):
    """Script test session fixture"""

    from nicos import session
    session.__class__ = ScriptSessionTest
    session.__init__('TestScriptSession')
    yield session
    session.shutdown()
Пример #2
0
    def run(cls, appname, maindevname=None, setupname=None, pidfile=True,
            daemon=False, start_args=None):
        if daemon == 'systemd':
            cls._notify_systemd(appname, "STATUS=initializing session")
        elif daemon:
            daemonize()
        else:
            setuser()

        def quit_handler(signum, frame):
            maindev.quit(signum=signum)

        def reload_handler(signum, frame):
            if hasattr(maindev, 'reload'):
                maindev.reload()

        def status_handler(signum, frame):
            if hasattr(maindev, 'statusinfo'):
                maindev.statusinfo()

        session.__class__ = cls
        try:
            session.__init__(appname, daemonized=daemon)
            maindev = cls._get_maindev(appname, maindevname, setupname)

            signal.signal(signal.SIGINT, quit_handler)
            signal.signal(signal.SIGTERM, quit_handler)
            if hasattr(signal, 'SIGUSR1'):
                signal.signal(signal.SIGUSR1, reload_handler)
                signal.signal(signal.SIGUSR2, status_handler)

            if pidfile and daemon != 'systemd':
                writePidfile(appname)

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

        if daemon == 'systemd':
            cls._notify_systemd(appname, "STATUS=starting main device")

        start_args = start_args or ()
        maindev.start(*start_args)

        if daemon == 'systemd':
            cls._notify_systemd(appname, "READY=1\nSTATUS=running")

        maindev.wait()

        session.shutdown()
        if pidfile and daemon != 'systemd':
            removePidfile(appname)
Пример #3
0
    def run(cls, setup, code, mode=SLAVE, appname='script'):
        session.__class__ = cls

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

        # Load the initial setup and handle becoming master.
        session.handleInitialSetup(setup, mode)

        # Execute the script code and shut down.
        exec_(code, session.namespace)
        session.shutdown()
Пример #4
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()
Пример #5
0
    def run(cls, setup='startup', simulate=False):
        # Assign the correct class to the session singleton.
        session.__class__ = cls
        session.__init__('nicos')
        session._stoplevel = 0
        session._in_sigint = False

        # Load the initial setup and handle becoming master.
        session.handleInitialSetup(setup, simulate and SIMULATION or SLAVE)

        # Fire up an interactive console.
        try:
            session.console()
        finally:
            # After the console is finished, cleanup.
            if session.mode != SIMULATION:
                session.log.info('shutting down...')
            session.shutdown()
Пример #6
0
def run_script_session(session, setup, code):
    session.handleInitialSetup(setup)
    try:
        exec(code, session.namespace)
    finally:
        session.shutdown()
Пример #7
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()