def run(self): try: with Pyro4.Daemon(host=str(self.ip), port=int(constant.SERVER_PORT)) as daemon: chordURI = daemon.register(self._chord) directory = os.path.dirname( str(self._chord.guid) + "/repository/") if not os.path.exists(directory): os.makedirs(directory) with Pyro4.locateNS(host="35.212.249.77", port=int(constant.SERVER_PORT)) as ns: ns.register(str(self._chord.guid), chordURI) if not os.path.isfile(constant.CHORD_PRIV_PEM): if not os.path.isfile(constant.CHORD_PUB_PEM): privKey, pubKey = self._chord.createKeys() f = open(constant.CHORD_PRIV_PEM, 'wb+') f.write(b64decode(privKey)) f.close() f = open(constant.CHORD_PUB_PEM, 'wb+') f.write(b64decode(pubKey)) f.close() f = open(constant.CHORD_PRIV_PEM, 'rb') private_key = serialization.load_pem_private_key( f.read(), password=None, backend=default_backend()) f.close() privPem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) self._chord.addKey(self._chord, b64encode(privPem).decode('UTF-8')) daemon.requestLoop() except Exception as e: print("Unable to start the server")
def pyro_daemon(name, obj, random_suffix=False, ip=None, port=None, ns_conf={}): """ Register object with name server (starting the name server if not running yet) and block until the daemon is terminated. The object is registered under `name`, or `name`+ some random suffix if `random_suffix` is set. """ if random_suffix: name += '.' + hex(random.randint(0, 0xffffff))[2:] import Pyro4 with getNS(**ns_conf) as ns: with Pyro4.Daemon(ip or get_my_ip(), port or 0) as daemon: # register server for remote access uri = daemon.register(obj, name) ns.remove(name) ns.register(name, uri) logger.info("%s registered with nameserver (URI '%s')" % (name, uri)) daemon.requestLoop()
def __init__(self, name, states, defaultState, host="localhost"): self.name = name self.host = host self.states = states if defaultState not in states: raise ValueError, "defaultState {} is not in the list of allowed states {}".format( defaultState, states) self.defaultState = defaultState self.currentState = self.defaultState self.daemonActive = True # Create Pyro Daemon daemon = Pyro4.Daemon(host=host) nameserver = Pyro4.locateNS() uri = daemon.register(self) nameserver.register("signal.{}".format(self.name), uri) pub.sendMessage("Signal.{}.daemon".format(self.name), daemon=daemon) print "Signal {} set up.".format(self.name) # Run the server daemon.requestLoop(self.serverActive)
def main(): counter = 0 while counter != 5: try: daemon = Pyro4.Daemon() ns = Pyro4.locateNS() f = FrontEnd(daemon) url = daemon.register(f) ns.register("frontend", url) print("Listening: ", url) daemon.requestLoop() print("Exit loop") daemon.close() f.timestamp = 0 f.write() print("Daemon closed") break except Pyro4.errors.CommunicationError: print("Attempt ", counter, " out of 5") print( "Servers are not found. Sleeping for 10 seconds and trying again..." ) sleep(10) counter = counter + 1
def main(): remoteLibrary = Pyro4.expose(bookDB.bookDB) db = bookDB.bookDB("mylib") daemon = Pyro4.Daemon(host="193.136.131.82") # Localiza o Name Server ns = Pyro4.locateNS(host="193.136.128.108", port=9090) print (ns) try: ns.createGroup(':libraries') except: pass # Regista a base de dados do servidor no Name Server uri = daemon.register(db, "BookDB-80931") ns.register("BookDB-80931", uri) try: daemon.requestLoop() finally: daemon.shutdown()
#!/usr/bin/env python # -*- coding: utf-8 -* import base64 import Pyro4 import numpy as np from detect_text_emotion import detect_text_emotion @Pyro4.expose class sentiment_text_service(object): def emotion_text_prediction_java(self, texto): returnValue = detector.predict_sentimiento(texto) print returnValue return returnValue[0] def emotion_text_prediction_pythonweb(self, texto): returnValue = detector.predict_sentimiento(texto) print returnValue return returnValue[0] detector = detect_text_emotion("data/corpus_model.m") daemon = Pyro4.Daemon("localhost", 25315) # make a Pyro daemon uri = daemon.register(sentiment_text_service, "text_service", True) print("Ready...") print("Uri: ", uri) daemon.requestLoop()
def init_server(self): self.daemon = Pyro4.Daemon() # make a Pyro daemon ns = Pyro4.locateNS() # find the name server uri = self.daemon.register(self.db) # register the greeting maker as a Pyro object ns.register("db_util", uri) # register the object with a name in the name server print("Rmi Server Ready.")
server = threading.Thread(target=thread_function, args=(1, )) server.start() time.sleep(1) #Pyro4.config.SERIALIZERS_ACCEPTED.add('pickle') #@expose as wrapper function: book_data = book("Bruno", "1", 2, 3) ExposedClass = Pyro4.expose(book) db = ExposedClass() daemon = Pyro4.Daemon( host='194.210.176.234' ) #my local IP wget -qO- http://ipecho.net/plain | xargs echo #uri2 = daemon.register(book_data,"book") #Send a object (data) uri = daemon.register(db, "book_class") #Send bookDB class ns = Pyro4.locateNS(host='127.0.0.1', port=9090) # python3 -m Pyro4.naming ns.register("book", uri) #print(uri) #Try also uri print("Running...") daemon.requestLoop()
from pyage.solutions.evolution.selection import TournamentSelection logger = logging.getLogger(__name__) agents_count = int(os.environ['AGENTS']) logger.debug("AGGREGATE, %s agents", agents_count) agents = generate_agents("agent", agents_count, AggregateAgent) aggregated_agents = unnamed_agents(2, Agent) stop_condition = lambda: StepLimitStopCondition(100) size = 500 operators = lambda: [ FloatRastriginEvaluation(), TournamentSelection(size=55, tournament_size=30), AverageFloatCrossover(size=size), UniformFloatMutation(probability=0.05, radius=1) ] initializer = lambda: FloatInitializer(500, size, -10, 10) address_provider = address.SequenceAddressProvider migration = Pyro4Migration locator = RandomLocator ns_hostname = lambda: os.environ['NS_HOSTNAME'] pyro_daemon = Pyro4.Daemon() daemon = lambda: pyro_daemon stats = TimeStatistics
self._hopcount_delay = delay def get_hopcount_delay(self): return self._hopcount_delay def set_daemon_obj(self, ref): self._daemon_obj = ref def stoppig(self): self._daemon_obj.shutdown() self._daemon_obj.close() sys.exit() if __name__ == '__main__': peerId = int(sys.argv[1]) hostinfo = sys.argv[2] hostname = hostinfo.split(":")[0] hostport = int(hostinfo.split(":")[1]) Pyro4.config.HOST = hostname daemon_obj = Pyro4.Daemon(hostname, hostport) print("peerId: {0} running with below uri".format(peerId), flush=True) #start peer client/server request loop pig = Peer({'id': peerId, 'daemon': daemon_obj}) Pyro4.Daemon.serveSimple({pig: "peer"}, ns=False, verbose=True, daemon=daemon_obj, host=hostname, port=hostport)
def daemonize(self, host: Optional[str] = None, port: int = 0) -> Tuple[str, str]: """ Starts a server in a new process. Args: host (str): Host where the server must be started port (int): Listening port for the server. Returns: pid (str): PID of the daemon process. uri (str): URI of the remote server. Raises: ClusterServerError: When the server was not started correctly """ self._id = self._get_id() r_fd, w_fd = os.pipe() pid = os.fork() if pid == 0: # Child code try: # Close the read pipe, as the child will just notify when the # process start. os.close(r_fd) w = os.fdopen(w_fd, 'w') with Pyro4.Daemon(host=host, port=port) as daemon: logging.info('Registering daemon') uri = daemon.register(self) self._daemon = daemon with open(self.pid_filepath, 'w') as f: logging.info('PID {}. Saving to file'.format( os.getpid())) f.write(str(os.getpid())) with open(self.uri_filepath, 'w') as f: logging.info('URI {}. Saving to file'.format(uri)) f.write(str(uri)) # Avoid IO errors with stderr and stdout, redirect them to # a logfile. # Close stdout and stderr os.close(1) os.close(2) # Logfile will be opened to fd 1 (stdout) with open(self.log_filepath, 'w') as f: # Assign the same file to fd 2 (stderr) os.dup(1) try: logging.info('Starting the Pyro4 server') w.write('ok') w.flush() daemon.requestLoop() except Exception as e: w.write('ko') logging.error(e) os._exit(1) except Exception as e: print(e) finally: # Make sure that always is written something to the pipe, to # avoid blocking the parent process. w.write('finish') w.close() os._exit(0) else: os.close(w_fd) # Wait for the child message r = os.fdopen(r_fd) r.read(1) r.close() if not os.path.isfile(self.pid_filepath): self.cleanup() raise errors.ClusterServerError('PID file not found') with open(self.pid_filepath, 'r') as f: spid = f.read() try: os.kill(int(spid), 0) except OSError as e: # If EPERM is the error we don't have permissions to send the # signal to the process, but it exists. if e.errno != errno.EPERM: logging.error('Server have not started') self.cleanup() raise errors.ClusterServerError( 'Server process does not exist') with open(self.uri_filepath, 'r') as f: uri = f.read() return (spid, uri)
def share_local_object(object_name, whitelist=None, host="localhost", port=9090): """ Share a local object of the given name over the network. :param str object_name: name of the local object :param whitelist: shared functions/classes of the local object as tuple pairs (module, function) or (module, class); whitelist all (do not filter) if None or empty :type whitelist: [(str,str)] or None :param str host: ip address of the local name server :param port: port of the local sharing server :type port: int or str This function shares a custom object with whitelisted attributes through a custom implementation. It is more secure but more limited as functionality since it requires serialization extensions. """ Pyro4.config.AUTOPROXY = True Pyro4.config.REQUIRE_EXPOSE = False port = int(port) if isinstance(port, str) else port # pyro daemon try: pyro_daemon = Pyro4.Daemon(host=host) LOG.debug("Pyro4 daemon started successfully") pyrod_running = False # address already in use OS error except OSError: pyro_daemon = Pyro4.Proxy("PYRO:" + Pyro4.constants.DAEMON_NAME + "@" + host) pyro_daemon.ping() LOG.debug("Pyro4 daemon already started, available objects: %s", pyro_daemon.registered()) pyrod_running = True # name server try: ns_server = Pyro4.locateNS(host=host, port=port) LOG.debug("Pyro4 name server already started") nsd_running = True # network unreachable and failed to locate the nameserver error except (OSError, Pyro4.errors.NamingError): from Pyro4 import naming ns_uri, ns_daemon, _bc_server = naming.startNS(host=host, port=port) ns_server = Pyro4.Proxy(ns_uri) LOG.debug("Pyro4 name server started successfully with URI %s", ns_uri) nsd_running = False # main retrieval of the local object module = importlib.import_module(object_name) def proxymethod(fun): """Decorator to autoproxy all callables.""" def wrapper(*args, **kwargs): rarg = fun(*args, **kwargs) def proxify_type(rarg): if rarg is None or type(rarg) in (bool, int, float, str): # pylint: disable=C0123 return rarg if isinstance(rarg, tuple): return tuple(proxify_type(e) for e in rarg) if isinstance(rarg, list): return [proxify_type(e) for e in rarg] if isinstance(rarg, dict): return { proxify_type(k): proxify_type(v) for (k, v) in rarg.items() } pyro_daemon.register(rarg) return rarg import types if isinstance(rarg, types.GeneratorType): def generator_wrapper(): for nxt in rarg: yield proxify_type(nxt) return generator_wrapper() return proxify_type(rarg) return wrapper class ModuleObject: # pylint: disable=R0903 """Module wrapped for transferability.""" for fname, fobj in inspect.getmembers(module, inspect.isfunction): if not whitelist or (object_name, fname) in whitelist: setattr(ModuleObject, fname, staticmethod(proxymethod(fobj))) for cname, cobj in inspect.getmembers(module, inspect.isclass): if not whitelist or (object_name, cname) in whitelist: setattr(ModuleObject, cname, staticmethod(proxymethod(cobj))) local_object = ModuleObject() # we should register to the pyro daemon before entering its loop uri = pyro_daemon.register(local_object) if not pyrod_running: loop = DaemonLoop(pyro_daemon) loop.start() if not nsd_running: loop = DaemonLoop(ns_daemon) loop.start() # we should register to the name server after entering its loop ns_server.register(object_name, uri) LOG.info("Local object '%s' sharing - ready", object_name) loop.join()
parser.add_argument( "--obj_port", "-op", dest='obj_port', action='store', default=0, type=int, help= "Specify a port on which to register daemon. Default is 0 (random).") return parser if __name__ == '__main__': parsed = parse_args("Start a basic server").parse_args() bs = BasicServer() print("Attempting to register server on name server") with Pyro4.Daemon(host='localhost', port=parsed.obj_port) as daemon: server_uri = daemon.register(bs, objectId=bs.__class__.__name__) print("Daemon URI is {}".format(server_uri)) try: with Pyro4.locateNS(port=parsed.ns_port, host=parsed.ns_host) as ns: ns.register('BasicServer', server_uri) except Pyro4.errors.NamingError as err: print( "Couldn't find specified nameserver, not registering daemon on nameserver." ) daemon.requestLoop()
default=False) pydb.logconfig.add_log_level_to_parser(parser) args = parser.parse_args() pydb.logconfig.set_log_level(args.loglevel) logger = logging.getLogger('pydbserver') logger.info('### logging started at %s local time. ###', time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())) pydb.config.read_config() db_dir = determine_database_directory(args.basepath) main_db = pydb.maindb.build(db_dir, schema_dir=get_schema_dir(), enable_db_sync=not args.no_sync) def term_handler(): main_db.hard_commit_all() atexit.register(term_handler) daemon = Pyro4.Daemon(port=args.pyro_port) daemon.register(main_db, objectId=args.pyro_name) comm_data_store = pydb.commdatastore.CommDataStore( os.path.join(db_dir, 'friends.db'), get_schema_dir()) daemon.register(comm_data_store, objectId=args.comm_data_store_name) daemon.requestLoop()
def __init__(self): sys.excepthook = Pyro4.util.excepthook self.daemon = Pyro4.Daemon( host=Pyro4.socketutil.getInterfaceAddress("www.google.com"))
def assign_handler(self, button_name, handler): self.handlers[button_name] = handler def button_clicked(self, name): print(name) if name in self.handlers: self.handlers[name]() if __name__ == '__main__': gui = GUI() gui.buttonhandler = ButtonHandler() ip = socket.gethostbyname(socket.gethostname()) daemon = Pyro4.Daemon(ip) client = RemoteClient(gui) client_uri = daemon.register(client) PyroClientThread(daemon).start() gameserver = Pyro4.Proxy('PYRONAME:example.pacmanserver') print('Connected to gameserver.') def new_room(): gameserver.new_room(ip, client_uri) update_rooms() gui.startgamebutton.config(state=NORMAL) gui.buttonhandler.assign_handler('create_room', new_room)
import Pyro4 import pickle import main from measurement import output_measurements # python -m Pyro4.naming -n 10.10.4.167 @Pyro4.expose class MeasurementCore(object): def predict(self, pickled_picture, weight, height): picture = pickle.loads(pickled_picture) viz_image, hmr_verts, adjusted_verts, m_adjusted_verts, adjusted_weight, adjusted_height = main.predict( picture, weight, height) measurements = output_measurements(m_adjusted_verts) return pickle.dumps((measurements, viz_image, hmr_verts, adjusted_verts, adjusted_weight, adjusted_height), protocol=0) if __name__ == "__main__": daemon = Pyro4.Daemon('10.10.4.167') # make a Pyro daemon ns = Pyro4.locateNS() # find the name server uri = daemon.register( MeasurementCore) # register the greeting maker as a Pyro object ns.register("measurement.api", uri) # register the object with a name in the name server print("Ready.") daemon.requestLoop( ) # start the event loop of the server to wait for calls
def start(self, ip, port, password, retry=float("inf")): """Start WorkerServer and ssh daemon and connect to nameserver.""" self.logger.info("starting up and connecting to %s:%d" % (ip, port)) #store for reconnection attempts self._ip = ip self._port = port self._password = password #Pyro4.config.HMAC_KEY = password tries = 1 self._ns = None while not self._ns: try: self._ns = Pyro4.locateNS(ip, port, hmac_key=password) except Pyro4.errors.NamingError: if tries < retry: self.logger.warn( "Unable to locate Nameserver. Trying again in 5 seconds..." ) time.sleep(5) tries += 1 else: self.logger.error("Unable to locate Nameserver.") sys.exit() self.config = Pyro4.Proxy(self._ns.lookup("config")) self.config._pyroHmacKey = password self.ip = self.config.get_worker_ip(self.get_hostname()) if (not self.ip): self.ip = Tools.guess_ip() if not self.config.has_section(self.get_hostname()): self.config.add_section(self.get_hostname()) self.config.set(self.get_hostname(), "ip", self.ip) self.logger.warn( """FrontendServer did not know IP of this host (check configuration for hostname). Guessed: %s""" % self.ip) self.logger.info("configuring and starting ssh daemon...") self.sshManager = SSH_Manager(folder=self.ssh_folder, ip=self.ip, port=self.config.get_sshd_port(), user=self.config.get("all", "sshuser")) self.sshManager.start_sshd() self._pyrodaemon = Pyro4.Daemon(host=self.ip) self._pyrodaemon._pyroHmacKey = password uri = self._pyrodaemon.register(self) self._ns.register(self._get_pyroname(), uri) uri = self._pyrodaemon.register(self.mnManager) self._ns.register(self._get_pyroname() + ".mnManager", uri) uri = self._pyrodaemon.register(self.sshManager) self._ns.register(self._get_pyroname() + ".sshManager", uri) atexit.register(self._stop) self.logger.info("looking for manager application...") manager_uri = self._ns.lookup("MaxiNetManager") if (manager_uri): self._manager = Pyro4.Proxy(manager_uri) self._manager._pyroHmacKey = self._password self.logger.info("signing in...") if (self._manager.worker_signin(self._get_pyroname(), self.get_hostname())): self.logger.info("done. Entering requestloop.") self._started = True self._looping_thread = threading.Thread( target=self._pyrodaemon.requestLoop) self._looping_thread.daemon = True self._looping_thread.start() else: self.logger.error("signin failed.") else: self.logger.error("no manager found.")
""" import Pyro4 import bookDB #s.connect((host, port)) #falta à classe as cenas para fazer a comunicacao server client, logo faço: remoteLibrary = Pyro4.expose(bookDB.bookDB) db = bookDB.bookDB("mylib") #remoteBook vai ter tudo o que vem do bookDB mas as cenas do Pyro #vai entao ter o modulo de comunicacao e o dispatch #o = remoteBookDB() #crio o obj como se fosse local #create a Pyro server with defined host daemon = Pyro4.Daemon(host="194.210.157.245") #194.210.157.245 #hostname -I # create remote obj uri and make it available to be accessible remotely uri = daemon.register(db, "bookDB") print(uri) #locauriuri ns = Pyro4.locateNS(host="146.193.41.139", port=9090) #register the uri of this server in the name server, naming it "elnome" ns.register("elnome", uri) #start request loop daemon.requestLoop() #pyro4-nsc -n 146.193.41.139 list #list all servers
del parent[self.basename(path)] return 0 except Exception as e: return -1 def rename(self, src, dst): if self.find_node(src) is None: print >> sys.stderr, "src doesn't exist!" self.vfs_errno = ENOENT return -1 if self.find_node(dst) is not None: print >> sys.stderr, "dst exists!" self.vfs_errno = EEXISTS return -1 dst_parent = self.find_parent(dst) src_parent = self.find_parent(src) dst_parent[self.basename(dst)] = src_parent[self.basename(src)] del src_parent[self.basename(src)] return 0 # main daemon = Pyro4.Daemon(port=5559) #unixsocket="mem_fs") uri = daemon.register(mem_fs(), "mem_fs") print "uri=", uri daemon.requestLoop()
self._name = marketname self._symbols = symbols def quotes(self): while True: symbol = random.choice(self.symbols) yield symbol, round(random.uniform(5, 150), 2) time.sleep(random.random() / 2.0) @property def name(self): return self._name @property def symbols(self): return self._symbols if __name__ == "__main__": nasdaq = StockMarket("NASDAQ", ["AAPL", "CSCO", "MSFT", "GOOG"]) newyork = StockMarket("NYSE", ["IBM", "HPQ", "BP"]) # for example purposes we will access the daemon and name server ourselves and not use serveSimple with Pyro4.Daemon(host="localhost", port=23245) as daemon: nasdaq_uri = daemon.register(nasdaq) newyork_uri = daemon.register(newyork) with Pyro4.locateNS() as ns: ns.register("example.stockmarket.nasdaq", nasdaq_uri) ns.register("example.stockmarket.newyork", newyork_uri) print("Stockmarkets available.") daemon.requestLoop()
print(full_path) if(os.path.isfile(full_path)): return 'Tidak bisa membuat file, file sudah ada', None try: with open(full_path, 'wb'): os.utime(full_path, None) return None, 'File sudah dibuat' except Exception as e: err = str(e) return err.replace(self.sharing_folder['base'],''), None # def main(): # Pyro4.Daemon.serveSimple( # { # Worker: "worker" # }, # ns=False, host="127.0.0.1", port=9000) with Pyro4.Daemon(host=Pyro4.socketutil.getIpAddress(None)) as daemon: # create a unique name for this worker (otherwise it overwrites other workers in the name server) worker_name = "Worker_%d@%s" % (os.getpid(), socket.gethostname()) print("Starting up worker", worker_name) uri = daemon.register(Warehouse) with Pyro4.locateNS() as ns: ns.register(worker_name, uri, metadata={"kelompok3.worker2"}) daemon.requestLoop() if __name__ == "__main__": main()
if self.inventory is None or self.inventory is False: self.inventory = getPrimaryServer(self.ns) resp = getattr(self.inventory, fn)(*args) attemptCount = 1 while type(resp) is dict and '__serverStatus' in resp and resp['__serverStatus'] == 'crashed': print('Called replica crashed. Trying again...') if attemptCount >= 10: break self.inventory = getPrimaryServer(self.ns, self.inventory) resp = getattr(self.inventory, fn)(*args) attemptCount += 1 return resp @Pyro4.expose def getFoods(self): return self.request('getContents', []) @Pyro4.expose def processOrder(self, order): return self.request('order', [order]) print('Just Hungry frontend startup...') with Pyro4.locateNS() as ns: inventory = getPrimaryServer(ns) with Pyro4.Daemon() as daemon: uri = daemon.register(JustHungryFrontend(inventory, ns)) ns.register('justhungry.frontend', uri) daemon.requestLoop() ns.remove('justhungry.frontend') print('Just Hungry frontend shutdown...')
action='store') parser.add_argument('--name', '-n', dest='pyro_name', help='Sets the Pyro4 name for the server', action='store', default="comservice") parser.add_argument('--port', '-p', dest='pyro_port', help='Sets the Pyro4 port for the server', action='store', default=4513, type=int) pydb.logconfig.add_log_level_to_parser(parser) args = parser.parse_args() pydb.logconfig.set_log_level(args.loglevel) print "Pyro port: %s" % args.pyro_port daemon = Pyro4.Daemon(port=args.pyro_port) # make a Pyro daemon commserver_uri = daemon.register( cs, objectId=args.pyro_name) # register the db object as a Pyro object print "Comm Service PYRO Server URI: " + str(commserver_uri) daemon.requestLoop( ) # start the event loop of the server to wait for calls cs.stop()
else: return 0 def getOrders(self): #server = connect() return self.server.getOrders() # uri1 = input("What is the Pyro uri of server1 ? ").strip() # uri2 = input("What is the Pyro uri of server2 ? ").strip() # # name = input("What is your name? ").strip() # greeting_maker = Pyro4.Proxy(uri) # get a Pyro proxy to the greeting object # print(greeting_maker.get_fortune(name)) # call method normally # server1 = Pyro4.Proxy("PYRONAME:server1") # server2 = Pyro4.Proxy("PYRONAME:server2") # print(server1.getmessage()) # print(server1.setmessage("newmessage")) # print(server1.getmessage()) # print(server2.avg(1,2,3)) # print(server2.max(2,2,3)) daemon = Pyro4.Daemon() # make a Pyro daemon ns = Pyro4.locateNS() # find the name server uri = daemon.register(FrontEnd) # register the greeting maker as a Pyro object ns.register("front_end", uri) print("Ready") daemon.requestLoop()
def __init__(self, engine): threadutil.Thread.__init__(self) self.pyroserver = remote.GameServer(engine) self.pyrodaemon = Pyro4.Daemon() self.ns = Pyro4.locateNS() self.setDaemon(True)
def runServer(server, port, nathost, natport, nshost, nsport, appName, hkey, app, daemon=None, metadata=None): """ Runs a simple application server :param str server: Host name of the server (internal host name) :param int port: Port number on the server where daemon will listen (internal port number) :param str nathost: Hostname of the server as reported by nameserver, for secure ssh tunnel it should be set to 'localhost' (external host name) :param int natport: Server NAT port as reported by nameserver (external port) :param str nshost: Hostname of the computer running nameserver :param int nsport: Nameserver port :param str appName: Name of registered application :param instance app: Application instance :param str hkey: A password string :param daemon: Reference to already running daemon, if available. Optional parameter. :param metadata: set of strings that will be the metadata tags associated with the object registration. See PyroUtil.py for valid tags. The metadata string "connection:server:port:nathost:natport" will be authomatically generated. :raises Exception: if can not run Pyro4 daemon """ externalDaemon = False if not daemon: try: daemon = Pyro4.Daemon(host=server, port=int(port), nathost=nathost, natport=Util.NoneOrInt(natport)) #daemon._pyroHmacKey = hkey.encode(encoding='UTF-8') #needed probably in future log.info('Pyro4 daemon runs on %s:%s using nathost %s:%s' % (server, port, nathost, natport)) except Exception: log.exception( 'Can not run Pyro4 daemon on %s:%s using nathost %s:%s' % (server, port, nathost, natport)) raise exit(1) else: externalDaemon = True ns = connectNameServer(nshost, nsport, hkey) #register agent; register exposed class #ExposedApp = Pyro4.expose(app)172.30.0.1 #Check if application name already exists on a nameServer try: (uri, mdata) = ns.lookup(appName, return_metadata=True) except Pyro4.errors.NamingError: pass else: log.warning( 'Application name \'%s\' is already registered on name server, overwriting.' % appName) uri = daemon.register(app) try: app.registerPyro(daemon, ns, uri, appName, externalDaemon=externalDaemon) except AttributeError as e: # catch attribute error (thrown when method not defined) log.warning('Can not register daemon on for application %s' % appName) except: log.exception( 'Can not register daemon on %s:%s using nathost %s:%s on nameServer' % (server, port, nathost, natport)) raise exit(1) # generate connection metadata entry metadata.add('%s:%s' % (NS_METADATA_host, server)) metadata.add('%s:%s' % (NS_METADATA_port, port)) metadata.add('%s:%s' % (NS_METADATA_nathost, nathost)) metadata.add('%s:%s' % (NS_METADATA_natport, natport)) ns.register(appName, uri, metadata=metadata) log.debug('NameServer %s has registered uri %s' % (appName, uri)) log.debug( 'Running runAppServer: server:%s, port:%s, nathost:%s, natport:%s, nameServer:%s, nameServerPort:%s, applicationName:%s, daemon URI %s' % (server, port, nathost, natport, nshost, nsport, appName, uri)) daemon.requestLoop()
def main(args, returnWithoutLooping=False): from optparse import OptionParser parser = OptionParser() parser.add_option("-H", "--host", default="localhost", help="hostname to bind server on (default=localhost)") parser.add_option("-p", "--port", type="int", default=0, help="port to bind server on") parser.add_option("-u", "--unixsocket", help="Unix domain socket name to bind server on") parser.add_option("-n", "--naming", action="store_true", default=False, help="register with nameserver") parser.add_option("-N", "--nameserver", action="store_true", default=False, help="also start a nameserver") parser.add_option("-v", "--verbose", action="store_true", default=False, help="verbose output") parser.add_option("-q", "--quiet", action="store_true", default=False, help="don't output anything") parser.add_option("-k", "--key", help="the HMAC key to use") options, args = parser.parse_args(args) if options.verbose: options.quiet = False if not options.quiet: print("Starting Pyro's built-in test echo server.") if os.name != "java": Pyro4.config.SERVERTYPE = "multiplex" hmac = (options.key or "").encode("utf-8") Pyro4.config.HMAC_KEY = hmac or Pyro4.config.HMAC_KEY if not options.quiet and Pyro4.config.HMAC_KEY: print("HMAC_KEY set to: %s" % Pyro4.config.HMAC_KEY) nameserver = None if options.nameserver: options.naming = True nameserver = startNameServer(options.host) d = Pyro4.Daemon(host=options.host, port=options.port, unixsocket=options.unixsocket) echo = EchoServer() echo.verbose = options.verbose objectName = "test.echoserver" uri = d.register(echo, objectName) if options.naming: host, port = None, None if nameserver is not None: host, port = nameserver.uri.host, nameserver.uri.port ns = naming.locateNS(host, port) ns.register(objectName, uri) if options.verbose: print("using name server at %s" % ns._pyroUri) if nameserver is not None: if nameserver.bc_server: print("broadcast server running at %s" % nameserver.bc_server.locationStr) else: print("not using a broadcast server") else: if options.verbose: print("not using a name server.") if not options.quiet: print("object name: %s" % objectName) print("echo uri: %s" % uri) print("echoserver running.") if returnWithoutLooping: return d, echo, uri # for unit testing else: d.requestLoop(loopCondition=lambda: not echo.must_shutdown) d.close()
@Pyro4.expose class Calculadora(object): def computar(self, operando1, operando2, operation): if (operation == '+'): return operando1 + operando2 elif (operation == '-'): return operando1 - operando2 elif (operation == '*'): return operando1 * operando2 elif (operation == '/'): try: return operando1 / operando2 except ZeroDivisionError: return "ERRO! Em uma divisão, o 2º operando não pode ser 0 (zero)." else: return "ERRO! O caractere informado não representa um operando (+, -, *, /)." print("Iniciando servidor...\n") daemon = Pyro4.Daemon() # Cria um Pyro daemon ns = Pyro4.locateNS() # Procura um name server uri = daemon.register(Calculadora) # Registra Calculadora como um objeto Pyro ns.register("calc.calculadora", uri) # Registra o objeto com um nome no nameserver print("Servidor pronto para uso.\n\nAperte CTRL+C para encerrar.") daemon.requestLoop() # Inicia um loop que espera por conexoes
def put(self, queue, message): self.queues[queue].put(message) def size(self, queue): return self.queues[queue].qsize() def delete(self, queue): del self.queues[queue] def purge(self, queue): while True: try: self.queues[queue].get(blocking=False) except Empty: break # launch a Kombu Broker daemon with the command: # ``python -m kombu.transport.pyro`` if __name__ == "__main__": print("Launching Broker for Kombu's Pyro transport.") with pyro.Daemon() as daemon: print("(Expecting a Pyro name server at {0}:{1})" .format(pyro.config.NS_HOST, pyro.config.NS_PORT)) with pyro.locateNS() as ns: print("You can connect with Kombu using the url " "'pyro://{0}/kombu.broker'".format(pyro.config.NS_HOST)) uri = daemon.register(KombuBroker) ns.register("kombu.broker", uri) daemon.requestLoop()