Exemple #1
0
def bind_socket(socket, address, retry_timeout=-1):
    r"""Bind a socket to an address, getting a random port as necessary.

    Args:
        socket (zmq.Socket): Socket that should be bound.
        address (str): Address that socket should be bound to.
        retry_timeout (float, optional): Time (in seconds) that should be
            waited before retrying to bind the socket to the address. If
            negative, a retry will not be attempted and an error will be
            raised. Defaults to -1;

    Returns:
        str: Address that socket was bound to, including random port if one
            was used.

    """
    try:
        param = parse_address(address)
        if (param['protocol'] in ['inproc', 'ipc']) or (param['port']
                                                        is not None):
            socket.bind(address)
        else:
            port = socket.bind_to_random_port(address)
            address += ":%d" % port
    except zmq.ZMQError as e:  # pragma: debug
        if (retry_timeout < 0):
            # if (e.errno not in [48, 98]) or (retry_timeout < 0):
            # print(e, e.errno)
            raise e
        else:
            logging.debug("Retrying bind in %f s", retry_timeout)
            tools.sleep(retry_timeout)
            address = bind_socket(socket, address)
    return address
def stop_matlab(screen_session,
                matlab_engine,
                matlab_session,
                keep_engine=False):  # pragma: matlab
    r"""Stop a Matlab shared engine session running inside a detached screen
    session.

    Args:
        screen_session (str): Name of the screen session that the shared
            Matlab session was started in.
        matlab_engine (MatlabEngine): Matlab engine that should be stopped.
        matlab_session (str): Name of Matlab session that the Matlab engine is
            connected to.
        keep_engine (bool, optional): If True, the references to the engine will be
            removed so it is not deleted. Defaults to False.

    Raises:
        RuntimeError: If Matlab is not installed.

    """
    if not _matlab_installed:  # pragma: no matlab
        raise RuntimeError("Matlab is not installed.")
    if keep_engine and (matlab_engine is not None):
        if '_matlab' in matlab_engine.__dict__:
            matlab_engine.quit()
        return
    # Remove weakrefs to engine to prevent stopping engine more than once
    if matlab_engine is not None:
        # Remove weak references so engine not deleted on exit
        eng_ref = weakref.getweakrefs(matlab_engine)
        for x in eng_ref:
            if x in matlab.engine._engines:
                matlab.engine._engines.remove(x)
        # Either exit the engine or remove its reference
        if matlab_session in matlab.engine.find_matlab():
            try:
                matlab_engine.eval('exit', nargout=0)
            except matlab.engine.EngineError:
                pass
        else:  # pragma: no cover
            matlab_engine.__dict__.pop('_matlab', None)
    # Stop the screen session containing the Matlab shared session
    if screen_session is not None:
        if matlab_session in matlab.engine.find_matlab():
            os.system(('screen -X -S %s quit') % screen_session)
        T = TimeOut(5)
        while ((matlab_session in matlab.engine.find_matlab())
               and not T.is_out):
            debug("Waiting for matlab engine to exit")
            sleep(1)
        if (matlab_session in matlab.engine.find_matlab()):  # pragma: debug
            raise Exception("stop_matlab timed out at %f s" % T.elapsed)
def start_matlab(skip_connect=False):  # pragma: matlab
    r"""Start a Matlab shared engine session inside a detached screen
    session.

    Args:
        skip_connect (bool, optional): If True, the engine is not connected.
            Defaults to False.

    Returns:
        str: Name of the screen session running matlab.

    Raises:
        RuntimeError: If Matlab is not installed.

    """
    if not _matlab_installed:  # pragma: no matlab
        raise RuntimeError("Matlab is not installed.")
    old_matlab = set(matlab.engine.find_matlab())
    screen_session = str('cis_matlab' +
                         datetime.today().strftime("%Y%j%H%M%S") +
                         '_%d' % len(old_matlab))
    try:
        args = [
            'screen', '-dmS', screen_session, '-c',
            os.path.join(os.path.dirname(__file__), 'matlab_screenrc'),
            'matlab', '-nodisplay', '-nosplash', '-nodesktop', '-nojvm', '-r',
            '"matlab.engine.shareEngine"'
        ]
        subprocess.call(' '.join(args), shell=True)
        T = TimeOut(10)
        while ((len(set(matlab.engine.find_matlab()) - old_matlab) == 0)
               and not T.is_out):
            debug('Waiting for matlab engine to start')
            sleep(1)  # Usually 3 seconds
    except KeyboardInterrupt:  # pragma: debug
        args = ['screen', '-X', '-S', screen_session, 'quit']
        subprocess.call(' '.join(args), shell=True)
        raise
    if (len(set(matlab.engine.find_matlab()) -
            old_matlab) == 0):  # pragma: debug
        raise Exception("start_matlab timed out at %f s" % T.elapsed)
    new_matlab = list(set(matlab.engine.find_matlab()) - old_matlab)[0]
    # Connect to the engine
    matlab_engine = None
    if not skip_connect:
        matlab_engine = connect_matlab(new_matlab, first_connect=True)
    return screen_session, matlab_engine, new_matlab
Exemple #4
0
def fibServer(args):

    sleeptime = float(args[0])
    print('Hello from Python rpcFibSrv: sleeptime = %f' % sleeptime)

    # Create server-side rpc conneciton using model name
    rpc = CisRpcServer("rpcFibSrv", "%d", "%d %d")

    # Continue receiving requests until error occurs (the connection is closed
    # by all clients that have connected).
    while True:
        print('rpcFibSrv(P): receiving...')
        retval, rpc_in = rpc.rpcRecv()
        if not retval:
            print('rpcFibSrv(P): end of input')
            break

        # Compute fibonacci number
        print('rpcFibSrv(P): <- input %d' % rpc_in[0], end='')
        pprev = 0
        prev = 1
        result = 1
        fib_no = 1
        arg = rpc_in[0]
        while fib_no < arg:
            result = prev + pprev
            pprev = prev
            prev = result
            fib_no = fib_no + 1
        print(' ::: ->(%2d %2d)' % (arg, result))

        # Sleep and then send response back
        sleep(float(sleeptime))
        flag = rpc.rpcSend(arg, result)
        if not flag:
            print('rpcFibSrv(P): ERROR sending')
            break

    print('Goodbye from Python rpcFibSrv')
    sys.exit(0)
Exemple #5
0
from cis_interface.tools import sleep

sleep(1)
print('Python model')