Esempio n. 1
0
def server():
    class SsdpSenderService(rpyc.Service):
        from ssdp_sender import SsdpSender as exposed_SsdpSender

    from rpyc.utils.server import ThreadedServer
    t = ThreadedServer(SsdpSenderService, port = 18861, protocol_config = {"allow_public_attrs" : True})
    t.start()
Esempio n. 2
0
class Test_Ssh(unittest.TestCase):
    def setUp(self):
        # setup an SSH context. on linux this would be as simple as
        # sshctx = SshContext("myhost")
        # assuming your user is configured to connect using authorized_keys
        
        if sys.platform == "win32":
            # on my windows box, it's a little more complicated:
            self.server = None
            sshctx = SshContext("hollywood.xiv.ibm.com", ssh_program = r"c:\Program Files\Git\bin\ssh.exe",
                user = "******", keyfile = r"c:\users\sebulba\.ssh\id_rsa")
            # make sure a classic server is running on remote-host:18888
            self.conn = rpyc.classic.ssh_connect(sshctx, "18888")
        else:
            # assume "ssh localhost" is configured to run without asking for password 
            self.server = ThreadedServer(SlaveService, hostname = "localhost", 
                ipv6 = False, port = 0, auto_register=False)
            t = threading.Thread(target=self.server.start)
            t.setDaemon(True)
            t.start()
            time.sleep(0.5)
            sshctx = SshContext("localhost")
            self.conn = rpyc.classic.ssh_connect(sshctx, self.server.port)

    def tearDown(self):
        self.conn.close()
        if self.server:
            self.server.close()

    def test_simple(self):
        print( "server's pid =", self.conn.modules.os.getpid())
        self.conn.modules.sys.stdout.write("hello over ssh\n")
        self.conn.modules.sys.stdout.flush()
Esempio n. 3
0
File: rpc.py Progetto: pombreda/MoaT
class RPCserver(Collected,Jobber):
	"""A channel server"""
	storage = RPCservers
	def __init__(self,name,host,port):
		self.name = name
		self.host=host
		self.port=port
		self.server = ThreadedServer(gen_rpcconn(name), hostname=host,port=port,ipv6=True, protocol_config = {"safe_attrs":set(("list","__unicode__","year","month","day","days","date","time","hour","minute","second","seconds","microseconds","ctx","items","iteritems")).union(DEFAULT_CONFIG["safe_attrs"])})
		self.server.listener.settimeout(None)
		self.start_job("job",self._start)
		super(RPCserver,self).__init__()

	def _start(self):
		self.server.start()

	def delete(self,ctx=None):
		self.server.close()
		self.server = None
		super(RPCserver,self).delete()

	def list(self):
		for r in super(RPCserver,self).list():
			yield r
		yield ("host",self.host)
		yield ("port",self.port)
		yield ("server",repr(self.server))
Esempio n. 4
0
 def close(self):
     ThreadedServer.close(self)
     if self.igd_mapping:
         try:
             self.igd.DeletePortMapping(self.port, 'TCP')
         except Exception as e:
             self.logger.info('IGD Exception: {}/{}'.format(type(e), e))
Esempio n. 5
0
class Test_Ssh(unittest.TestCase):
    def setUp(self):
        if sys.platform == "win32":
            self.server = None
            os.environ["HOME"] = os.path.expanduser("~")
            self.remote_machine = SshMachine("localhost")
        else:
            # assume "ssh localhost" is configured to run without asking for password
            self.server = ThreadedServer(SlaveService, hostname = "localhost",
                ipv6 = False, port = 18888, auto_register=False)
            self.server._start_in_thread()
            self.remote_machine = SshMachine("localhost")

    def tearDown(self):
        if self.server:
            self.server.close()

    def test_simple(self):
        conn = rpyc.classic.ssh_connect(self.remote_machine, 18888)
        print( "server's pid =", conn.modules.os.getpid())
        conn.modules.sys.stdout.write("hello over ssh\n")
        conn.modules.sys.stdout.flush()

    def test_connect(self):
        conn2 = rpyc.ssh_connect(self.remote_machine, 18888, service=MasterService)
        conn2.modules.sys.stdout.write("hello through rpyc.ssh_connect()\n")
        conn2.modules.sys.stdout.flush()
Esempio n. 6
0
def main():
    logging.basicConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument('--pid', action='store', dest='pid', default='/var/tmp/harvester_rpc.pid',
                        help='pid filename')
    parser.add_argument('--port', dest='port', type=int, default=18861,
                        help='the TCP port to bind to')
    parser.add_argument('--backlog', dest='backlog', type=int, default=10,
                        help='backlog for the port')
    parser.add_argument('--stdout', action='store', dest='stdout', default='/var/tmp/harvester_rpc.out',
                        help='stdout filename')
    parser.add_argument('--stderr', action='store', dest='stderr', default='/var/tmp/harvester_rpc.err',
                        help='stderr filename')
    options = parser.parse_args()
    # make daemon context
    outfile = open(options.stdout, 'w+')
    errfile = open(options.stderr, 'w+')
    dc = daemon.DaemonContext(
                pidfile=daemon.pidfile.PIDLockFile(options.pid),
                stdout=outfile,
                stderr=errfile)
    # run thread server
    with dc:
        from rpyc.utils.server import ThreadedServer
        t = ThreadedServer(RpcBot, port=options.port, backlog=options.backlog,
                            protocol_config={"allow_all_attrs": True})
        t.start()
    # finalize
    outfile.close()
    errfile.close()
Esempio n. 7
0
class IPCServer(threading.Thread):
    def __init__(self, manager, port=None):
        super(IPCServer, self).__init__(name='ipc_server')
        self.daemon = True
        self.manager = manager
        self.host = '127.0.0.1'
        self.port = port or 0
        self.password = ''.join(random.choice(string.letters + string.digits) for x in range(15))
        self.server = None

    def authenticator(self, sock):
        channel = rpyc.Channel(rpyc.SocketStream(sock))
        password = channel.recv()
        if password != self.password:
            channel.send(AUTH_ERROR)
            raise rpyc.utils.authenticators.AuthenticationError('Invalid password from client.')
        channel.send(AUTH_SUCCESS)
        return sock, self.password

    def run(self):
        DaemonService.manager = self.manager
        self.server = ThreadedServer(
            DaemonService, hostname=self.host, port=self.port, authenticator=self.authenticator, logger=log
        )
        # If we just chose an open port, write save the chosen one
        self.port = self.server.listener.getsockname()[1]
        self.manager.write_lock(ipc_info={'port': self.port, 'password': self.password})
        self.server.start()

    def shutdown(self):
        self.server.close()
Esempio n. 8
0
def main():
    from solarsan import logging
    logger = logging.getLogger(__name__)
    from solarsan.cluster.models import Peer
    from solarsan.conf import rpyc_conn_config
    from rpyc.utils.server import ThreadedServer
    #from rpyc.utils.server import ThreadedZmqServer, OneShotZmqServer
    from setproctitle import setproctitle
    from .service import CLIService
    import rpyc

    title = 'SolarSan CLI'
    setproctitle('[%s]' % title)

    local = Peer.get_local()
    cluster_iface_bcast = local.cluster_nic.broadcast
    # Allow all public attrs, because exposed_ is stupid and should be a
    # f*****g decorator.
    #t = ThreadedZmqServer(CLIService, port=18863,
    #t = OneShotZmqServer(CLIService, port=18863,
    t = ThreadedServer(CLIService, port=18863,
                       registrar=rpyc.utils.registry.UDPRegistryClient(ip=cluster_iface_bcast,
                                                                       #logger=None,
                                                                       logger=logger,
                                                                       ),
                       auto_register=True,
                       logger=logger,
                       #logger=None,
                       protocol_config=rpyc_conn_config)
    t.start()
Esempio n. 9
0
class Test_SSL(object):
    '''
    created key like that
    http://www.akadia.com/services/ssh_test_certificate.html
    
    openssl req -newkey rsa:1024 -nodes -keyout mycert.pem -out mycert.pem
    '''

    def setup(self):
        self.key = os.path.join( os.path.dirname(__file__) , "server.key")
        self.cert =  os.path.join( os.path.dirname(__file__) , "server.crt")
        print( self.cert, self.key )
        
        authenticator = SSLAuthenticator(self.key, self.cert)
        self.server = ThreadedServer(SlaveService, hostname = "localhost",port = 18812, 
            auto_register=False, authenticator = authenticator)
        self.server.logger.quiet = False
        t = threading.Thread(target=self.server.start)
        t.start()

    def teardown(self):
        self.server.close()
    
    def test_ssl_conenction(self):
        c = rpyc.classic.ssl_connect("localhost", port = 18812, 
            keyfile=self.key, certfile=self.cert)
        print( repr(c) )
        print( c.modules.sys )
        print( c.modules["xml.dom.minidom"].parseString("<a/>") )
        c.execute("x = 5")
        assert c.namespace["x"] == 5
        assert c.eval("1+x") == 6
        c.close()
Esempio n. 10
0
class Test_tlslite(object):
    def setup(self):
        authenticator = TlsliteVdbAuthenticator.from_dict(users)
        self.server = ThreadedServer(rpyc.SlaveService, hostname = "localhost", 
            authenticator = authenticator, auto_register = False)
        self.server.logger.quiet = True
        thread.start_new(self.server.start, ())
        time.sleep(1) # make sure the server has initialized, etc.
    
    def teardown(self):
        self.server.close()
    
    def test_successful(self):
        c = rpyc.classic.tlslite_connect("localhost", "spam", "eggs", 
            port = self.server.port)
        print ("server credentials = %r" % (c.root.getconn()._config["credentials"],))
        print (c.modules.sys)
        c.close()

    def _expect_fail(self, username, password):
        print ("expecting %s:%s to fail" % (username, password))
        c = rpyc.classic.tlslite_connect("localhost", username, password, 
            port = self.server.port)
    
    @raises(TLSError)
    def test_wrong_tokens(self):
        self._expect_fail("spam", "bar")

    @raises(TLSError)
    def test_wrong_tokens2(self):
        self._expect_fail("bloop", "blaap")
Esempio n. 11
0
def server():
    'Launch a server'
    try:
        server = ThreadedServer(MyService, port = 12345, protocol_config = {"allow_all_attrs": True}, auto_register = False)
        server.start()
    except Exception:
        raise
    return True
Esempio n. 12
0
def start_service():
    t = ThreadedServer(SimService, port=18861, auto_register=True)
    try:
        t.start()
    except KeyboardInterrupt:
        t.stop()
        logging.warning("SINGINT caught from user keyboard interrupt")
        sys.exit(1)
def main():
    global handler
    open('./nohup.out','w').close()
    handler=word_handler()
    handler.add_embedding_file('all')
    for date in xrange(2005,2014):
        handler.add_embedding_file(date)
    sr=ThreadedServer(Listener,port=22222,auto_register=False)
    sr.start()
Esempio n. 14
0
def serve_threaded(options):
    t = ThreadedServer(SlaveService, hostname = options.host, 
        port = options.port, reuse_addr = True, 
        authenticator = options.authenticator, registrar = options.registrar,
        auto_register = options.auto_register)
    t.logger.quiet = options.quiet
    if options.logfile:
        t.logger.console = open(options.logfile, "w")
    t.start()
Esempio n. 15
0
class Server(Thread):
    
    def __init__(self):
        Thread.__init__(self)
        self.setDaemon(True)
        self.server = ThreadedServer(MyService, port = DEFAULT_SERVER_PORT)
       
    def run(self):
        self.server.start()
Esempio n. 16
0
    def __init__(self, *args, **kwargs):

        if not "stream" in kwargs:
            raise ValueError("missing stream_class argument")

        if not "transport" in kwargs:
            raise ValueError("missing transport argument")

        self.stream_class = kwargs["stream"]
        self.transport_class = kwargs["transport"]
        self.transport_kwargs = kwargs["transport_kwargs"]
        self.pupy_srv = kwargs["pupy_srv"]

        self.igd_mapping = False
        self.igd = None

        if 'igd' in kwargs:
            self.igd = kwargs['igd']
            del kwargs['igd']

        ping = self.pupy_srv.config.get('pupyd', 'ping')
        self.ping = ping and ping not in (
            '0', '-1', 'N', 'n', 'false', 'False', 'no', 'No'
        )

        if self.ping:
            try:
                self.ping_interval = int(ping)
            except:
                self.ping_interval = 2

            self.ping_timeout = self.pupy_srv.config.get('pupyd', 'ping_interval')
        else:
            self.ping_interval = None
            self.ping_timeout = None

        del kwargs["stream"]
        del kwargs["transport"]
        del kwargs["transport_kwargs"]
        del kwargs["pupy_srv"]

        ThreadedServer.__init__(self, *args, **kwargs)

        if not self.igd:
            try:
                self.igd = IGDClient()
            except UPNPError as e:
                pass

        if self.igd and self.igd.available:
            try:
                self.igd.AddPortMapping(self.port, 'TCP', self.port)
                self.igd_mapping = True
            except UPNPError as e:
                self.logger.warn(
                    "Couldn't create IGD mapping: {}".format(e.description))
Esempio n. 17
0
 def __init__(self, *args, **kwargs):
     ThreadedServer.__init__(self, *args, **kwargs)
     PyNuvoServer.Send = self._send
     self.con = Serial( 'COM1', 57600 )
     self.active = True
     self.thread_receive = threading.Thread(target = self.receive)
     self.thread_receive.start()
     #Do remaining initialization on Thread so that Windows service can start quicker
     self.thread_init = threading.Thread(target = self._bg_init)
     self.thread_init.start()
Esempio n. 18
0
def main():
    setup_logging()

    logger.info("Starting server ...")
    locale.setlocale(locale.LC_ALL, "")

    args = parse_args()
    start_background_worker(args)
    wrapService = WrapService(net_io_counters, logs)
    s = ThreadedServer(wrapService, port=5050,  protocol_config={"allow_public_attrs":True})
    s.start()
Esempio n. 19
0
def remote_service_operator(DATA):
        """
        starts the (threaded) service which exposes the 
        RPYC_service factory class to remote RPYC clients.
            
        This is the function which should be called in the main function,
        there is no need for hiding it in a class.
        """
        CS  = CustomizedService(DATA)
        t = ThreadedServer(CS, port = DATA.localhost.port)#, protocol_config = {"allow_public_attrs" : True})
        t.start()
Esempio n. 20
0
def rpcThread():
    class TrafficMonitor(rpyc.Service):
        def on_connect(self):
            pass
        def on_disconnect(self):
            pass
        def exposed_get_traffic(self):
            return g_rate

    from rpyc.utils.server import ThreadedServer
    t = ThreadedServer(TrafficMonitor, port = PORT)
    t.start()
Esempio n. 21
0
    def main(self):
        logger.info("Worker just staring.")
        print "THIS IS IMPORTANT COPY THOSE TO WEB CONTROL PANEL"
        print "PUBLIC HOSTNAME: ",get_public_hostname()
        print "PUBLIC IP ADDR:  ",get_public_ip_addr()
        print "IP ADDR:         ",get_ip_addr()
        print "WILL START IN 2 SECONDS                        !"
        import time
        time.sleep(2)

        from rpyc.utils.server import ThreadedServer
        t = ThreadedServer(PreciousWorkerService, port=get_worker_port())
        t.start()
def start_server(config_file):
    defaults = {
        'hostname':'localhost', 
        'lport':'31337',
        'ipv6':'off',
        'backlog':'10',
    }
    config = ConfigParser.SafeConfigParser(defaults)
    config.readfp(open(config_file, 'r'))
    lport = config.getint("Network", 'lport')
    host = config.get("Network", 'hostname').strip()
    agent = ThreadedServer(WeaponSystem, hostname=host, port=lport)
    agent.start()
Esempio n. 23
0
 def _run(self):
     message = 'Starting m_server daemon...' 
     logger.info("%s" % message)
     # 开启监听服务
     while True:
         try:
             s = ThreadedServer(ManagerService, port=PORT, auto_register=False)  
             # 启动rpyc服务监听、接受、响应请求
             s.start()
         except Exception, e:
             message = 'Starting service error!'
             logger.error(message)
             sys.exit()
Esempio n. 24
0
class MasterRPC:
    def __init__(self, redis_host, redis_port=6379, slaves_db=3, port=8780, auto_register=False):
        global slaves, ws
        slaves = SlaveStorage(slaves_db, redis_host, redis_port)
        ws = websocket.create_connection("ws://localhost:8000/soc")
        self.server = ThreadedServer(MasterRPCService, port=port, auto_register=auto_register)

        logging.info("Start master on port %d..." % port)
        ws.send("Start master on port %d..." % port)
        # http.post("Start master on port %d..." % port)

        self.server.start()

    def close(self):
        self.server.close()
Esempio n. 25
0
class mavLinkServiceClientThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.t = None

    def run(self):
        from rpyc.utils.server import ThreadedServer
        self.t = ThreadedServer(MavLinkRpycClientService, port = 18862)
        #self.t._closed = False
        self.t.start()

    def stop(self):
        if not(self.t==None):
            #self.t.stop() # https://docs.python.org/2/library/thread.html
            self.t.exit()
Esempio n. 26
0
    def inner_run(self, *args, **options):
        """
        Starts a threaded server on given hostname:port (defaults to 127.0.0.1:4444)
        """

        # defaults
        hostname = '0.0.0.0'
        port = '4444'

        if len(args) == 1:
            hostname, port = args[0].split(':')

        print "Starting serviced on {}:{}".format(hostname, port)
        server = ThreadedServer(CallService, port=int(port))
        server.start()
Esempio n. 27
0
 def target(host, port, threads=True):
     '''
     Start a process that will generate a new thread for every 
     connection. Each Component, in the graph, will be represented by a
     new dedicated connection for the proxy object representing that 
     component.
     '''
     from rpyc import SlaveService
     if threads:
         from rpyc.utils.server import ThreadedServer
         t = ThreadedServer(SlaveService, hostname=host, port=port)
     else:
         from rpyc.utils.server import ForkingServer
         t = ForkingServer(SlaveService, hostname=host, port=port)
     t.start()
Esempio n. 28
0
 def __init__(self, port, task_directory, course_factory, task_factory, ssh_manager_port=None, tmp_dir="./agent_tmp", sync_enabled=True):
     SimpleAgent.__init__(self, task_directory, course_factory, task_factory, ssh_manager_port, tmp_dir)
     self.sync_enabled = sync_enabled
     self.logger.debug("Starting RPyC server - inginious.backend connection")
     self._backend_server = ThreadedServer(self._get_agent_backend_service(), port=port,
                                           protocol_config={"allow_public_attrs": True, 'allow_pickle': True})
     self._backend_server.start()
Esempio n. 29
0
class TestRestricted(unittest.TestCase):
    def setUp(self):
        self.server = ThreadedServer(MyService, port = 0)
        self.thd = self.server._start_in_thread()
        self.conn = rpyc.connect("localhost", self.server.port)

    def tearDown(self):
        self.conn.close()
        self.server.close()
        self.thd.join()

    def test_restricted(self):
        obj = self.conn.root.get_one()
        self.assertEqual(obj.foo(), "foo")
        self.assertEqual(obj.bar(), "bar")
        self.assertRaises(AttributeError, lambda: obj.spam)
Esempio n. 30
0
 def setup(self):
     authenticator = TlsliteVdbAuthenticator.from_dict(users)
     self.server = ThreadedServer(rpyc.SlaveService, hostname = "localhost", 
         authenticator = authenticator, auto_register = False)
     self.server.logger.quiet = True
     thread.start_new(self.server.start, ())
     time.sleep(1) # make sure the server has initialized, etc.
Esempio n. 31
0
from rpyc.utils.server import ThreadedServer
from rpyopencl_service import RPyOpenCLService

RPYC_CFG = {
    "allow_all_attrs": True,
    "allow_pickle": True,
    "allow_public_attrs": True
}

if __name__ == "__main__":
    s = ThreadedServer(RPyOpenCLService, port=18861, protocol_config=RPYC_CFG)
    s.start()
Esempio n. 32
0
    def on_disconnect(self, conn):
        self.exposed_stop()

    def exposed_start(self):
        self.sensor.enable_disable_driver(True)
        self.started = True

    def exposed_stop(self):
        self.sensor.enable_disable_driver(False)
        self.started = False

    def exposed_get_data(self):
        if not self.started:
            self.sensor.enable_disable_driver(True)
        return self.sensor.get_data()

    def exposed_get_filtered_data(self):
        if not self.started:
            self.sensor.enable_disable_driver(True)
        return self.sensor.get_filtered_data()


if __name__ == "__main__":
    from rpyc.utils.server import ThreadedServer

    server = ThreadedServer(UltrasonicSensorService(),
                            port=11121,
                            auto_register=True)
    server.start()
#!/usr/bin/en python
import os
from rpyc import Service
from rpyc.utils.server import ThreadedServer


class remote_call_script(Service):
    def exposed_iamshell(self):
        return os.system("./iamshell.sh")

    def exposed_iamperl(self):
        return os.system("./iamperl.pl")

    def exposed_iampython(self):
        return os.system("./iampython.py")


s = ThreadedServer(remote_call_script, port=11111, auto_register=False)
s.start()
Esempio n. 34
0
        return

    def parse_config(self):
        config = self.config
        config_file = open(config, 'r')
        first_line = config_file.readline()
        idx = first_line.find(': ')
        num_node = int(first_line[idx + 2:])
        next_line = config_file.readline()
        host_field = []
        port_field = []
        while next_line:
            this_line = next_line
            idx = this_line.find(': ')
            idx2 = this_line.find(':', idx + 2)
            host_field.append(this_line[idx + 2:idx2])
            idx_next_line = this_line.find('\r\n', idx2)
            if idx_next_line != -1:
                port_field.append(int(this_line[idx2 + 1:idx_next_line]))
            else:
                port_field.append(int(this_line[idx2 + 1:]))
            next_line = config_file.readline()
        config_file.close()
        return num_node, host_field, port_field


if __name__ == '__main__':
    from rpyc.utils.server import ThreadedServer

    server = ThreadedServer(RaftNode(sys.argv[1], int(sys.argv[2]), int(sys.argv[3])), port=int(sys.argv[3]))
    server.start()
Esempio n. 35
0
        method as an RPC call

        CHANGE THIS METHOD TO RETURN THE APPROPRIATE RESPONSE
    '''

    def exposed_is_leader(self):
        return self.cur_leader == self.node_id


if __name__ == '__main__':
    config = sys.argv[1]
    node_id = int(sys.argv[2])
    port_no = int(sys.argv[3])

    log_filename = "log_node" + str(node_id) + ".log"
    logging.basicConfig(
        filename=log_filename,
        level=logging.DEBUG,
        format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s',
        datefmt='%H:%M:%S')

    logging.info("Run on port: " + str(port_no))

    from rpyc.utils.server import ThreadedServer
    server = ThreadedServer(RaftNode(config, node_id),
                            port=port_no,
                            protocol_config={
                                'allow_public_attrs': True,
                            })
    server.start()
Esempio n. 36
0
 def setUpClass(cls):
     cls.server = ThreadedServer(SlaveService, port=18878, auto_register=False)
     cls.server.logger.quiet = False
     cls.server._start_in_thread()
Esempio n. 37
0
        hour = str(now.hour).rjust(2, '0')
        minute = str(now.minute).rjust(2, '0')
        second = str(now.second).rjust(2, '0')
        day = str(now.day).rjust(2, '0')
        month = str(now.month).rjust(2, '0')
        year = str(now.year)
        return f'{hour}:{minute}:{second} - {day}/{month}/{year}'


if __name__ == "__main__":
    args = sys.argv[1:]
    if (len(args) == 3):
        [SERVER_NAME, SERVER_PORT, DIR_NAME] = args
        SERVER_PORT = int(SERVER_PORT)

        server = ThreadedServer(ApplicationServer, port=SERVER_PORT)

        conn = rpyc.connect(ROOT_ADDR, ROOT_PORT)
        response = conn.root.exposed_lookup(DIR_NAME)
        print(response['message'])

        if (response['success']):
            (addr, port) = response['data']

            SERVER_ADDR = socket.gethostbyname(socket.gethostname())
            my_address = (SERVER_ADDR, SERVER_PORT)

            conn = rpyc.connect(addr, port)
            response = conn.root.exposed_register(SERVER_NAME, my_address)
            print(response['message'])
Esempio n. 38
0
            with open(block_addr) as f:
                return f.read()

        def forward(self,block_uuid,data,minions):

            if debug_Mode:
                print("8888: forwaring to:")
                print(block_uuid, minions)
            minion = minions[0]
            minions = minions[1:]
            host, port = minion

            con = rpyc.connect(host, port=port)
            minion = con.root.Chunks()
            minion.put(block_uuid,data,minions)

        def exposed_delete_block(self,block_uuid):
            block_addr = DATA_DIR + str(block_uuid)
            if debug_Mode:
                print(" deleting ")
                print(block_addr)
            if not os.path.isfile(block_addr):
                return None
            os.remove(block_addr)
            return True


if __name__ == "__main__":
    if not os.path.isdir(DATA_DIR): os.mkdir(DATA_DIR)
    t = ThreadedServer(MinionService, port=8888)
    t.start()
        return scheduler.get_job(job_id)

    def exposed_get_jobs(self, jobstore=None):
        return scheduler.get_jobs(jobstore)

    def exposed_print_jobs(self, jobstore=None):
        return scheduler.print_jobs(jobstore)


if __name__ == '__main__':
    """初始化"""
    jobstores = {
        # 'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')  # SQLAlchemyJobStore指定存储链接 # 由于pickle sqlalchemy 报错 只能取消存储
    }
    executors = {
        'default': {'type': 'threadpool', 'max_workers': 20},  # 最大工作线程数20
        'processpool': ProcessPoolExecutor(max_workers=5)  # 最大工作进程数为5
    }
    scheduler = BackgroundScheduler()
    scheduler.configure(jobstores=jobstores, executors=executors)
    scheduler.start()
    protocol_config = {'allow_public_attrs': True}
    server = ThreadedServer(SchedulerService, port=12345, protocol_config=protocol_config)
    try:
        print("start ")
        server.start()
    except (KeyboardInterrupt, SystemExit):
        pass
    finally:
        scheduler.shutdown()
Esempio n. 40
0
has 4 states; "standby", "configuring", "available" and "unconfiguring"
and 6 events; "online", "offline", "configure done", "unconfigure done"
and "error". "online" and "offline" are external and the others are
generated internally.
"""
__author__ = 'David Terrett + Brian McIlwrath'

if __name__ == "__main__":
    from .states import sm
    import threading
    """ This starts the rpyc 'ThreadedServer' - this creates a new 
        thread for each connection on the given port
    """
    from .MasterControllerService import MasterControllerService
    from rpyc.utils.server import ThreadedServer
    server = ThreadedServer(MasterControllerService, port=12345)
    t = threading.Thread(target=server.start)
    t.setDaemon(True)
    t.start()
    """ For testing we can also run events typed on the terminal
    """
    # Read and process events
    while True:
        event = input('?')
        result = sm.post_event([event])
        if result == 'rejected':
            print('not allowed in current state')
        if result == 'ignored':
            print('command ignored')
        else:
            print('master controller state:', sm.current_state())
Esempio n. 41
0
def rpyc_start(sensor_instance):
    logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
    from rpyc.utils.server import ThreadedServer
    t = ThreadedServer(sensor_instance, port=9600, listener_timeout=60, logger=logging.getLogger())
    t.start()
Esempio n. 42
0
class ledService(rpyc.Service):
    def on_connect(self, conn):  # Do nothing when somebody connects
        pass

    def on_disconnect(self, conn):  # Do nothing when somebody disconnects
        pass

    def exposed_blink(
            self, ledName,
            ledMode):  # We expect a ledname and a blinking mode for it
        global ledModes
        ledModes[ledName.lower()] = ledMode.lower(
        )  # We set it globally so that our bgHandler can do the blinking
        logging.info("Setting led {} to {}".format(ledName, ledMode))
        return True


# -------------------------- Main ------------------------

if __name__ == "__main__":
    setupIO()
    runBootScript()

    # Start the background handler for the leds and buttons
    bgHandler_thread = threading.Thread(target=bgHandler)
    bgHandler_thread.start()

    # Start listening on a tcpport for commands. The commands are handled by ledService
    t = ThreadedServer(ledService, port=TCP_PORT)
    t.start()
Esempio n. 43
0
    def exposed_pass(self):
        pass

    def exposed_sh_generator(self,tag,name):
        create_source_config(tag,name)
        return sh_generator(tag,name)

    def exposed_del_job(self,job):
        return del_job(job)

    def exposed_check_cron(self,jobs):
        return check_cron(jobs)

    def exposed_add_sh_to_cron(self,name,sh,schedule):
        v = add_sh_to_cron(name,sh,schedule)
        print(v)
        return v

    def exposed_job_pauser(self,x):
        return job_pauser(x)    

if __name__ == "__main__":
    from rpyc.utils.server import ThreadedServer
    port = 18861
    cfg = {
        "allow_public_attrs": True,
        "allow_all_attrs": True
    }
    t = ThreadedServer(Server,port=port,protocol_config=cfg)
    print(f"Server started at :{port}")
    t.start()
            reducers.append(rpyc.async_(reducer.execute)(i, self.task, self.filename, self.KVServer_address, 
                                                       self.kvport))
            reducers[i].set_expiry(None)

        # wait till all reducers to completes their assigned task
        for reducer in reducers:
            while not reducer.ready:
                continue
     
    def exposed_destroy_cluster(self):
        
        # Terminate and delete all worker instances
        for ind in range(self.nmapper):
            self.gcpapi.delete_instance(self.project, self.zone, "mapper"+str(ind))
        for ind in range(self.nreducer):
            self.gcpapi.delete_instance(self.project, self.zone, "reducer"+str(ind))

        # Terminate KVServer
        logging.info('Cluster destroyed')
        
    
if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('config.ini')
    port = int(config['Master']['master_port'])
    rpyc.core.protocol.DEFAULT_CONFIG['sync_request_timeout'] = None
    t = ThreadedServer(Master, port = port, protocol_config = rpyc.core.protocol.DEFAULT_CONFIG)
    try:
        t.start()
    except Exception:
        t.stop()   
Esempio n. 45
0
import rpyc


class MemoryService(rpyc.Service):
    def on_connect(self):
        self._blob = {}

    def on_diconnect(self):
        pass

    def exposed_blob(self, caller_id, key, data=None):
        if not caller_id or (not caller_id in self._blob and not data):
            return ValueError('Invalid caller_id')
        if not data:
            return self._blob[caller_id].get(
                key, ValueError('Specified key does not exist'))
        if not caller_id in self._blob: self._blob[caller_id] = {}
        self._blob[caller_id][key] = data
        return True


if __name__ == '__main__':
    port = 9999 if len(sys.argv) < 2 else int(sys.argv[1])
    from rpyc.utils.server import ThreadedServer

    t = ThreadedServer(MemoryService, 'localhost', port=port)
    print('Running MemoryService on port %s. Use Ctrl+C to quit.' % (port))
    t.start()
    print('Killing MemoryService.')
        return n1

    # operação com um argumento String e valor de retorno String
    def exposed_send_string(self, string):
        return "Hello " + string 

    # operação com um argumento Person e valor de retorno PersonReply
    def exposed_send_person(self, person_received):
        person_reply = Person.PersonReply()
        person_reply.id = randint(1,10000)
        person_reply.name = person_received.name
        person_reply.stat = Person.Status.CADASTRADO
        return person_reply 

    # operação com um argumento Person e valor de retorno PersonReply
    def exposed_send_var_person(self, array_person):
        array_reply = []
        for person in array_person:
            person_reply = Person.PersonReply()
            person_reply.id = randint(1,10000)
            person_reply.name = person.name
            person_reply.stat = person.Status.CADASTRADO
            array_reply.append(person_reply)
        return array_reply 

if __name__ == "__main__":
    from rpyc.utils.server import ThreadedServer
    print("Iniciando servidor...")
    t = ThreadedServer(MyService, port=port, protocol_config = {"allow_public_attrs" : True})
    print("Servidor aberto")
    t.start()
Esempio n. 47
0
    # def on_disconnect(self, conn):
    #     # code that runs after the connection has already closed
    #     # (to finalize the service, if needed)

    # def exposed_get_answer(self, x): # this is an exposed method
    #     return np.ones(6)
    #     # return 42

    # exposed_the_real_answer_though = 43     # an exposed attribute

    # def get_question(self):  # while this method is not exposed
    #     return "what is the airspeed velocity of an unladen swallow?"


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='server')
    parser.add_argument(
        '--load-dir',
        help=
        'directory to load model (e.g.: ./exp_models/multi_miniright2_withvprev_withmindis_highrewvpref_training-v0/model4500.pt)'
    )
    parser.add_argument('--cuda',
                        default=True,
                        help='enable GPU (default: True)')
    args = parser.parse_args()

    from rpyc.utils.server import ThreadedServer
    # t = ThreadedServer(MyService(), port=18861)
    t = ThreadedServer(MyService(args.load_dir, args.cuda), port=18861)
    t.start()
Esempio n. 48
0
            file.write('\n'.join(lines))

        print('Map Reduce completed.')
        return 'Success'

    def exposed_destroy_cluser(self, cluster_id):
        self.__KVStore.removePersistentStorage()
        print('destroy cluster called', cluster_id)

    def __isMapTaskCompleted(self):
        pass

    def __startReducers(self):
        pass


if __name__ == "__main__":
    from rpyc.utils.server import ThreadedServer
    rpyc.core.protocol.DEFAULT_CONFIG['sync_request_timeout'] = None
    ip, master_port = config['masterNode']['internal_host'], config[
        'masterNode']['port']
    t = ThreadedServer(MapReduceMasterNode,
                       hostname=ip,
                       port=int(master_port),
                       protocol_config=rpyc.core.protocol.DEFAULT_CONFIG)
    try:
        print('Starting mapReduce server. Listening on port:', master_port)
        t.start()
    except Exception:
        t.stop()
Esempio n. 49
0
            description[0]
            for description in self.sqlite_service.cursor.description
        ]

        return table

    def exposed_quit(self) -> None:
        exit()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='TCP Server Program')
    parser.add_argument('-p',
                        metavar='PORT',
                        type=int,
                        default=1060,
                        help='TCP port (default 1060)')
    parser.add_argument('-d',
                        metavar='DATABASE',
                        type=str,
                        default='data.db',
                        help='Database (default data.db)')

    args = parser.parse_args()
    print(f'Server running on port {args.p} using {args.d}')

    service = classpartial(SqliteService, args.d)
    server = ThreadedServer(service, port=args.p)

    server.start()
Esempio n. 50
0
        self.My_Tank = MoveTank(OUTPUT_B, OUTPUT_C)
        self.Control = MediumMotor(OUTPUT_D)

    def status_check(self):
        self.Control.position = 0

    def exposed_run(self):

        self.My_Tank.on(-60, -60)

    def exposed_back(self):

        self.My_Tank.on(30, 30)

    def exposed_stop(self):

        self.My_Tank.off()

    def exposed_steering(self, degree=0):

        self.Control.on_for_degrees(30, degree, True, True)


if __name__ == '__main__':
    while input("Input 'start' for starting ") == 'start':
        s = ThreadedServer(Ev3Car, port=18812)
        s.start()
        print(s.listener)
    else:
        exit()
Esempio n. 51
0
import rpyc
from constRPYC import *  #-
from rpyc.utils.server import ThreadedServer


class Directory(rpyc.Service):
    registry = {}

    def exposed_register(self, server_name, ip_address, port_number):
        self.registry[server_name] = (ip_address, port_number)
        print(self.registry)
        return "Registro OK"

    def exposed_lookup(self, server_name):
        print(self.registry)
        return self.registry[server_name]


if __name__ == "__main__":
    server = ThreadedServer(Directory, port=D_PORT)
    server.start()
Esempio n. 52
0
                                                      precoLocal, cidade,
                                                      localizacao))
    databaseFile.close()

    adicionarRestaurante = input(
        'Inserido com Sucesso. Deseja Inserir outro Local ? ')

print('Servidor iniciado')


class RestauranteService(rpyc.Service):
    def exposed_pesquisaRestaurante(self, local):
        databaseFile = open('Databases/Restaurante.txt', 'r')
        print('Nova consulta para ' + local)

        message = '\n ====== Restaurantes ======\n'
        for line in databaseFile.readlines():
            campos = line.split(',')
            if campos[3].__contains__(local):
                message += '\nLocal: ' + campos[0] + '\n'
                message += 'Telefone: ' + campos[1] + '\n'
                message += 'Preço: ' + campos[2] + '\n'
                message += 'Localização: ' + campos[4] + '\n'

        databaseFile.close()
        return message


thread = ThreadedServer(RestauranteService, port=35002)
thread.start()
Esempio n. 53
0
    if config.standAlone:

        rpcSend.requestKinectPower(True)

        # try to grab an image
        kinectInit()
        tableHeight = 920    # 920 table height
        obstacles = obstacleMap(0,tableHeight)

        obstacle, distance, xAngle, yAngle = cartObstacleDetected()
        config.log(f"distance: {distance:.0f}, xAngle: {xAngle:.0f}, yAngle: {yAngle:.0f}")

        os._exit(5)


    # add thread to monitor distance during forward move of cart
    monitorThread = threading.Thread(target=monitorObstacles, args={})
    monitorThread.setName('monitorThread')
    monitorThread.start()

    # start rpc listener, does not return
    print(f"start listening on port {config.MY_RPC_PORT}")
    myConfig = {"allow_all_attrs": True, "allow_pickle": True}
    server = ThreadedServer(rpcReceive.rpcListener(), port=config.MY_RPC_PORT, protocol_config=myConfig)
    server.start()

    # code here never reached


Esempio n. 54
0
 def __init__(self, *args, port=18861, **kwargs):
     self.server = ThreadedServer(ModNASService, *args, port=port, **kwargs)
Esempio n. 55
0
from components.adas.AdaptiveCruiseController import AdaptiveCruiseController
from components.services.AbstractComponentService import AbstractComponentService


class ACCService(rpyc.Service, AbstractComponentService):

    ALIASES = ["AdaptiveCruise"]

    def on_connect(self, conn):
        self.acc = AdaptiveCruiseController.get_instance()

    def on_disconnect(self, conn):
        self.exposed_stop()

    def exposed_start(self):
        __speed_service = rpyc.connect_by_service("SpeedDriver")
        speed = __speed_service.root
        self.acc.enable_disable_driver(True, speed)
        self.started = True

    def exposed_stop(self):
        self.acc.enable_disable_driver(False, None)
        self.started = False


if __name__ == "__main__":
    from rpyc.utils.server import ThreadedServer

    server = ThreadedServer(ACCService(), port=11131, auto_register=True)
    server.start()
Esempio n. 56
0
def createRpyc(port):
    sr = ThreadedServer(TestService, port=port, auto_register=False)
    sr.start()
Esempio n. 57
0
            logging.info(f"Received with completed view task: {map_state}")

        try:
            # Always to get latest task and ignore other tasks
            self._resp_q.put(map_state, timeout=0.1)
            map_state.resp_state_err = "ok"
        except:
            map_state.resp_state_err = "error"
            logging.error(f"Cannot save completed view task", exc_info=True)

        return {
            "state_err": map_state.resp_state_err,
            "pos": (map_state.pos_x, map_state.pos_y, map_state.ort_xy)
        }


if __name__ == "__main__":
    logging.basicConfig(
        level=logging.DEBUG,
        format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        handlers=[
            logging.FileHandler("ViewerBackendService.log"),
            logging.StreamHandler()
        ])
    logging.info("Start Viewer Backend Service")

    viewer_service = ViewerService()

    t = ThreadedServer(viewer_service, port=viewer_service.port)
    t.start()
Esempio n. 58
0
def server():
    t = ThreadedServer(MyService, port=18861)
    t.start()
Esempio n. 59
0
        self.list_printlist = []
        self.list_downl = []

    def set_list_printlist(self, printlist):
        self.list_printlist = self.list_printlist + [printlist]

    def show(self):
        try:
            self.list_printlist[-1](self.filename)
        except:
            pass

    def upl(self, file, path):
        self.files = self.files + [file]
        self.filename = self.filename + [path]

    def set_calldownl(self, downloadlist):
        self.list_downl = self.list_downl + [downloadlist]

    def calldownl(self, num):
        bindata = self.files[num]
        fname = self.filename[num]
        self.list_downl[-1](bindata, fname)


if __name__ == "__main__":
    from rpyc.utils.server import ThreadedServer
    c = FileShareServer()
    t = ThreadedServer(Service, port=18863)
    t.start()
Esempio n. 60
0
from rpyc.utils.server import ThreadedServer
from time_service import TimeService

if __name__ == "__main__":
    s = ThreadedServer(TimeService)
    s.start()