def main(): set_context() host = create_host('http://127.0.0.1:1277') p1 = host.spawn('1', Echo) p2 = host.lookup('1') print 'p1 =', id(p1) print 'p2 =', id(p2) print p1 == p2 print p1 != p2 print p1 is p2 s = set() s.add(p1) s.add(p2) print len(s) print p1 print repr(p1) serve_forever()
self.proxies = [] def set_proxies(self, p1, p2): self.proxies.append(p1) self.proxies.append(p2) # print(self.proxies) def get_proxies(self): return self.proxies # sleep(5) # return 'hi' def read_future(self, future): print(future.result()) if __name__ == '__main__': set_context() h = create_host("http://127.0.0.1:12777") db = h.spawn('db', DB) # c = h.spawn('c', Consum) p1 = h.spawn('p1', DB) p2 = h.spawn('p2', DB) db.set_proxies(p1, p2) # result = c.get_proxies(db) # print result # sleep(1) serve_forever()
num = self.peers[torrent_hash].keys() num.remove(peer) peerResult = random.sample(num, 3) else: peerResult = self.peers[torrent_hash].keys() peerResult.remove(peer) return peerResult def announce(self, torrent_hash, peer): if not(self.peers.has_key(torrent_hash)): self.peers[torrent_hash] = {} self.peers[torrent_hash][peer] = 1 def update(self): for swamp in self.peers.keys(): for peer in self.peers[swamp].keys(): if self.peers[swamp][peer] == 0: del self.peers[swamp][peer] else: self.peers[swamp][peer] = 0 if __name__ == "__main__": set_context() host = create_host('http://127.0.0.1:1277/') track = host.spawn('tracker', Tracker) track.init() serve_forever()
try: n_peers = int(raw_input("Enter the number of peers: ")) except ValueError: print "Not a number" if gossip_type == 1: peer_class = Push elif gossip_type == 2: peer_class = Pull else: peer_class = Hybrid peers = [] set_context() h = create_host() printer = h.spawn('printer', Printer) tracker = h.spawn('tracker', Tracker) tracker.add_printer(printer) seed = h.spawn('seed', peer_class) seed.finish() seed.add_tracker(tracker) seed.add_printer(printer) seed.init_data('torrent.txt') for i in range(0, n_peers): peer = h.spawn("peer" + str(i), peer_class) peer.add_tracker(tracker) peer.add_printer(printer)
def get_clients(self): return self.clients.values() def remove_client(self, cli): del self.clients[cli] # print "stoped", cli if not self.clients.keys(): print "Server", self.id, "ended." def end(self): return not self.clients.keys() if __name__ == "__main__": set_context('green_thread') host = create_host('http://127.0.0.1:1679/') clies = [] servs = [] for si in xrange(SERVERS): serv = host.spawn('s' + str(si), Server) servs.append(serv) for i in xrange(CLIENTS): c = host.spawn(str(si) + str(i), Connecter) c.set_server(serv) serv.register_client(c) clies.append(c) print si, 'online' print "All nodes created. Starting..."
#!/usr/bin/python from pyactor.context import set_context, create_host, serve_forever if __name__ == '__main__': set_context() host = create_host('http://127.0.0.1:1303/') registry = host.lookup_url('http://127.0.0.1:6000/regis', 'Registry', 'registry') registry.bind('mapper3', host) serve_forever()
self.dicc.update(dic_map) self.finished -= 1 if self.finished == 0: self.stopCrono() self.registry.results("CW",self.dicc,self.timeinit) if __name__ == "__main__": global remote_master set_context() try: if len(sys.argv) != 3: raise IndexError ip = str(sys.argv[1]) ip_sv = str(sys.argv[2]) except IndexError: print "\n----------------\nERROR. Los argumentos no son válidos.\n----------------\nArgumentos:" print "\n\tpython reduce.py [ip_reducer] [ip_master]\n\n\t* si las ip's son 'localhost' = 127.0.0.1\n" shutdown() finally: if ip == "localhost": ip = "127.0.0.1" if ip_sv == "localhost": ip_sv = "127.0.0.1" host = create_host('http://%s:1700/' % (str(ip))) reduce = host.spawn("Reducer", "reduce/Reducer") print reduce print "\n\tCargando...\n" remote_master = host.lookup_url("http://%s:1500/regis"%ip_sv, 'Registry', 'master') remote_master.bind("Reducer", reduce) serve_forever()
''' Remote example with registry. CLIENT @author: Daniel Barcelona Pons ''' from pyactor.context import set_context, create_host, serve_forever if __name__ == "__main__": set_context() host = create_host('http://127.0.0.1:6001') registry = host.lookup_url('http://127.0.0.1:6000/regis', 'Registry', 's4_registry') registry.bind('host1', host) serve_forever()
""" Basic remote example sending tell messages. CLIENT @author: Daniel Barcelona Pons """ from pyactor.context import set_context, create_host, shutdown if __name__ == '__main__': set_context() host = create_host("http://127.0.0.1:1679") e1 = host.lookup_url("http://127.0.0.1:1277/echo1", 'Echo', 's1_server') e1.echo("Hi there!") # TELL message e1.echo("See ya!") shutdown()
#Validate the entry argument length numberOfArguments = len(sys.argv) if (numberOfArguments != 2): print "python client.py <mode>" exit(-1) #Check if mode is correct mode = sys.argv[1] if ((mode != "CW") and (mode != "WC")): print "ERROR: Mode has to be CW (counting words) or WC (words count)" exit(-1) IP_COMPUTER1 = "http://127.0.0.1" IP_COMPUTER2 = "http://127.0.0.1" host = create_host(IP_COMPUTER1 + ':1679') #Spawn the reducer reducerHost = host.lookup_url(IP_COMPUTER1 + ':' + str(1277) + '/', Host) reducer = reducerHost.spawn(1277, Reduce) reducer.setNumberOfMappers(4) remoteHost = host.lookup_url(IP_COMPUTER1 + ':' + str(1278) + '/', Host) host1 = remoteHost.spawn(1278, Map) remoteHost = host.lookup_url(IP_COMPUTER2 + ':' + str(1279) + '/', Host) host2 = remoteHost.spawn(1279, Map) remoteHost = host.lookup_url(IP_COMPUTER1 + ':' + str(1280) + '/', Host) host3 = remoteHost.spawn(1280, Map)
class PongActor(object): _tell = {'send', 'set_ping'} _ref = {'set_ping'} pongCount = 0 def set_ping(self, ping): self.ping = ping def send(self, msg): if isinstance(msg, SendPingMessage): # print 'pong' pong = SendPongMessage() self.ping.send(pong) self.pongCount = self.pongCount + 1 elif isinstance(msg, StopMessage): self.ping.send(msg) self.proxy.stop() else: raise Exception("Unsupported message: " + msg) if __name__ == '__main__': set_context() host = create_host("amqp://127.0.0.1:9000/") pong = host.spawn('pong', PongActor) serve_forever()
from pyactor.context import set_context, create_host, serve_forever if __name__ == "__main__": set_context() host = create_host('http://192.168.1.46:4323/') print 'host listening at port 4323' serve_forever()
myIp = ([ l for l in ( [ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1]]) if l ][0][0]) set_context() # clientb_host = create_host('http://10.0.2.15:' + str(port)) clientb_host = create_host('http://' + str(myIp) + ':' + str(port)) registry = clientb_host.lookup_url( 'http://' + str(ip_Registry) + ':1282/regis', 'Registry', 's4_registry') parametre = [] parametre = sub_arxius() hostWords = parametre[0] fi_temps1 = parametre[1] inici_temps2 = time.time() distribuir_feina() while not clientb_host.has_actor('myWrite'): time.sleep(0.001) while clientb_host.lookup('myWrite').get_Fin() is not True: time.sleep(0.001)
#!/usr/bin/env #-*- coding: utf-8 -*- from pyactor.context import set_context, create_host, sleep, shutdown, serve_forever import commands numMapers = 4 if __name__ == '__main__': set_context() i = 0 while i < numMapers: maper = create_host('http://127.0.0.1:600' + str(i)) r = maper.lookup_url('http://127.0.0.1:5000/regis', 'Registry', 'registry') r.subscribe(maper) i = i + 1 serve_forever()
self.proxies = [] def set_proxies(self, p1, p2): self.proxies.append(p1) self.proxies.append(p2) # print self.proxies def get_proxies(self): return self.proxies sleep(5) return 'hi' def read_future(self, future): print future.result() if __name__ == "__main__": set_context() h = create_host('http://127.0.0.1:1277') db = h.spawn('db', DB) # c = h.spawn('c', Consum) p1 = h.spawn('p1', DB) p2 = h.spawn('p2', DB) db.set_proxies(p1, p2) # result = c.get_proxies(db) # print result # sleep(1) serve_forever()
if __name__ == "__main__": ip = sys.argv[1] port = 6000 if len(sys.argv) == 2: pass elif len(sys.argv) == 3: ip = sys.argv[1] port = (sys.argv[2]) try: if (int(port) > 65535) or (int(port) < 0): print("Error, port must be 0-65535") exit(1) except ValueError: print "Incorrect port. Port must be 0-65535" exit(1) else: print("Incorrect arguments") exit(1) set_context() host = create_host('http://' + str(ip) + ':' + str(port) + '/') registry = host.spawn('regis', Registry) print 'Registry host(' + ip + ') listening at port ' + str(port) serve_forever()
from pyactor.context import set_context, create_host, serve_forever class Echo(object): _tell = ['echo', 'set_c', 'echoc'] _ask = [] _ref = ['set_c'] def echo(self, msg): print msg, self.id def set_c(self, future): print 'sending to another' # print future future.echoc('something') # print future.result(2) # future.add_callback('echoc') def echoc(self, future): print future.result(2), 'callback' if __name__ == "__main__": set_context('green_thread') host = create_host('http://127.0.0.1:1277/') e1 = host.spawn('echo1', Echo) serve_forever()
from pyactor.context import set_context, create_host, sleep, shutdown, interval, later, Host, serve_forever import Tracker import Sequencer import User if __name__ == '__main__': set_context() #User Host h = create_host('http://127.0.0.1:1242') user = h.spawn("user2", User.User) user.setID(2) #Tracker Host host = h.lookup_url('http://127.0.0.1:1220', Host) tracker = host.lookup_url('http://127.0.0.1:1220/TrackerID', Tracker.Tracker) user.joinTracker(tracker, h) user.setTracker(tracker) user.init_start(h) #Sequencer Host host2 = h.lookup_url('http://127.0.0.1:1230', Host) user.setHosts(h, host2) sleep(15) user.multicast("PAU") #user.multicastLamport("PAU")
remote_reducer.cw(self.words) else: print "\n\tEl programa seleccionado no se encuentra disponible.\n" if __name__ == "__main__": set_context() try: if len(sys.argv) != 4: raise IndexError id_mapper = int(sys.argv[1]) ip = str(sys.argv[2]) ip_sv = str(sys.argv[3]) except IndexError: print "\n----------------\nERROR. Los argumentos no son válidos.\n----------------\nArgumentos:" print "\n\tpython master.py [id_mapper] [ip_mapper] [ip_master]\n\n\t* si las ip's son 'localhost' = 127.0.0.1\n" shutdown() finally: if ip == "localhost": ip = "127.0.0.1" if ip_sv == "localhost": ip_sv = "127.0.0.1" host = create_host("http://%s:160%s/" % (ip, id_mapper)) map = host.spawn("Mapper", "mapper/Mapper") print map print "\n\tCargando...\n" remote_master = host.lookup_url("http://%s:1500/regis" % ip_sv, 'Registry', 'master') remote_master.bind("Mapper_%s" % str(id_mapper), map) serve_forever()
def off(self): shutdown() if __name__ == "__main__": set_context() #Obtenim un port lliure port = get_free_port() #Introduim una ip ip = set_ip() #Creamos el host con diferente puerto host = create_host('http://' + ip + ':' + str(port)) ip_registry = str(raw_input("Introdueix la ip del registry: ")) #Conseguimos la referencia a registry de manera remota registry = host.lookup_url('http://' + ip_registry + ':6000/regis', 'Registry', 'p1_registry') #Pedimos al usuario el nombre del fichero a modificar file_name = str(raw_input("Introdueix el nom del fitxer: ")) #Creamos un actor master para mostrar la infromacion al final del programa y borrar los archivos master = host.spawn('master', 'p1_master/Master', file_name) #Obtenemos un puerto libre para el servidor port_servidor = get_free_port()
self.next.take_token() def take_token(self): self.cnt += 1 if not self.is_finished(): self.next.take_token() if __name__ == '__main__': # set_context('green_thread') set_context('thread') print(f"TEST {NUM_NODES} nodes and {NUM_MSGS} messages.") port = 1260 host = [create_host(f"http://127.0.0.1:{port}/")] nf = host[0].spawn('ini', Node) np = nf for i in range(NUM_NODES - 2): port += 1 host.append(create_host(f"http://127.0.0.1:{port}/")) ni = host[i+1].spawn(str(i), Node) ni.set_next(np) np = ni port += 1 host.append(create_host(f"http://127.0.0.1:{port}/")) n1 = host[NUM_NODES-1].spawn('end', Node, ni)
raise NotFound() def lookup(self, name): if name in self.actors: return self.actors[name] else: return None def get_all(self): return self.actors.values() if __name__ == "__main__": set_context() hr = create_host("http://127.0.0.1:7777/") reducer = hr.spawn('Red', "mapReduce/Reducer") registry = hr.spawn('regis', Registry) for x in range(0, int(sys.argv[1])): os.system("nohup python spawn.py %s mapReduce &" % str(x)) sleep(2) reducer.start(int(sys.argv[1])) x = 0 vHost = {} vMap = {} for actor in registry.get_all(): vHost[x] = actor vMap[x] = vHost[x].spawn('Map%s' % str(x), "mapReduce/Mapper")
self.diccionariFinal = {} self.num=0 def reducer(self, diccionari, t): self.diccionariFinal=Counter(self.diccionariFinal)+Counter(diccionari) self.num=self.num+1 if self.num==numMapers: tempsf=time() print "Temps d'execucio: "+str(tempsf-t) print self.diccionariFinal if __name__ == '__main__': set_context() tempsi=time() #Creem master master = create_host('http://127.0.0.1:1234/') #Busquem el registry r=master.lookup_url('http://127.0.0.1:5000/regis', 'Registry', 'registry') #Creem el Reducer red=master.spawn('red', 'server/Reducer') #Executem els mapers i=0 while i<numMapers: i=i+1 #Executem els mapers per obtenir els diccionaris i els reduim amb el Reducer r.getMapers()[i-1].spawn('maper'+str(i), 'server/Maper').execute(i, red, tempsi) serve_forever()
''' from pyactor.context import set_context, create_host, sleep, shutdown class Echo(object): _tell = ['echo'] _ask = [] _ref = ['echo'] def echo(self, msg, pref=None): print msg, pref if __name__ == "__main__": set_context() h = create_host("http://127.0.0.1:6666/host") e1 = h.spawn('echo1', Echo) e1.echo('hello there !!', e1) h2 = create_host("http://127.0.0.1:7777/host") e2 = h2.spawn('echo1', Echo) e2.echo('hello 2', e1) sleep(1) e1.echo('hello 3', e2) sleep(1) shutdown() # or, to only stop one of them: # shutdown("http://127.0.0.1:7777/host")
class PongActor(object): _tell = ['send', 'set_ping'] _ref = ['set_ping'] pongCount = 0 def set_ping(self, ping): self.ping = ping def send(self, msg): if isinstance(msg, SendPingMessage): # print 'pong' pong = SendPongMessage() self.ping.send(pong) self.pongCount = self.pongCount + 1 elif isinstance(msg, StopMessage): self.ping.send(msg) self.proxy.stop() else: raise Exception("Unsupported message: " + msg) if __name__ == "__main__": set_context() host = create_host('amqp://127.0.0.1:9000/') pong = host.spawn('pong', PongActor) serve_forever()
print("hi", self.id) def get_proxies(self, db): future = db.get_proxies(future=True) # future.add_callback('read_future', db) print(future.result()) return future # while not future.done: # sleep(0.1) # proxies = future.result() # return proxies if __name__ == '__main__': set_context() h = create_host("http://127.0.0.1:12888") # db = h.spawn('db', DB) c = h.spawn('c', Consum) # p1 = h.spawn('p1', Consum) # p2 = h.spawn('p2', Consum) db = h.lookup_url("http://127.0.0.1:12777/db", 'DB', 'ffutureref') # db.set_proxies(p1, p2) try: result = c.get_proxies(db) print(result.result()) # db.read_future(result) except Exception as e: print(e)
#-*- coding: utf-8 -*- from pyactor.context import set_context, create_host, sleep, shutdown, serve_forever from collections import Counter from itertools import izip_longest class Registry(object): _tell = ['subscribe'] _ask = ['getMapers'] _ref = ['subscribe', 'getMapers'] def __init__(self): self.l = [] def subscribe(self, maper): print maper self.l.append(maper) def getMapers(self): return self.l if __name__ == '__main__': set_context() host = create_host('http://127.0.0.1:5000/') registry = host.spawn('regis', Registry) print 'Registry listening at port 5000' serve_forever()
return self.actors.values() def get_host(self): ret = [] for regitred in self.get_name(): if regitred[:4] == "host": ret.append(self.lookup(regitred)) return ret if __name__ == "__main__": set_context() myIp = ([ l for l in ([ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1]]) if l ][0][0]) host = create_host("http://" + str(myIp) + ":1282") # host = create_host('http://10.0.2.15:1282') registry = host.spawn('regis', Registry) print 'host listening at port 1282' serve_forever()
def active_thread(self): self.current_cycle += 1 for parent in self.__class__.__bases__: parent.active_thread(self) if __name__ == "__main__": if not found: print "Missing package bitarray https://pypi.python.org/pypi/bitarray" subprocess.call("./freePeerPorts.sh", shell=True) set_context() h = create_host("http://192.168.1.101:6970") type = [PushPeer, PullPeer, PushPullPeer] for i in range(3, 5): # sleep(randint(1, 5) / 10) # client = h.spawn("Peer" + str(i), choice(type)) client = h.spawn("Peer" + str(i), PushPullPeer) client.set_download_folder("Peer" + str(i)) client.add_torrent(Torrent("palabra.json")) client.add_torrent(Torrent("frase.json")) client.add_torrent(Torrent("parrafo.json")) client.run() for i in range(0, 1): genesis = h.spawn("Genesis" + str(i), PushPullPeer)
''' Basic remote example sending tell messages. CLIENT @author: Daniel Barcelona Pons ''' from pyactor.context import \ set_context, create_host, setRabbitCredentials, shutdown if __name__ == "__main__": setRabbitCredentials('daniel', 'passs') set_context() host = create_host('amqp://127.0.0.1:1679') e1 = host.lookup_url('amqp://127.0.0.1:1277/echo1', 'Echo', 's1_server') e1.echo('Hi there!') # TELL message e1.echo('See ya!') shutdown()
_tell = ['substract'] def add(self, x, y): return x + y def substract(self, x, y): print 'subtract', x - y def wait_a_lot(self): sleep(2) return 'ok' if __name__ == "__main__": set_context() host = create_host('http://127.0.0.1:6002') registry = host.lookup_url('http://127.0.0.1:6000/regis', 'Registry', 's4_registry') remote_host = registry.lookup('host1') if remote_host is not None: if not remote_host.has_actor('server'): server = remote_host.spawn('server', 's4_clientb/Server') else: server = remote_host.lookup('server') z = server.add(6, 7) print z server.substract(6, 5) t = server.add(8, 7) print t
msg = PingMessage() self.send(msg) else: msg = StopMessage() self.pong.send(msg) elif isinstance(msg, StopMessage): global working working = False self.proxy.stop() else: raise Exception("Unsupported message: " + msg.__class__.__name__) if __name__ == "__main__": set_context() host = create_host('amqp://127.0.0.1:9111/') pong = host.lookup_url('amqp://127.0.0.1:9000/pong', 'PongActor', 'rpong') ping = host.spawn('ping', PingActor, N, pong) pong.set_ping(ping) init = time() msg = StartMessage() ping.send(msg) while working: sleep(1) end = time()
class Registry(object): _ask = ['bind','lookup'] _ref = ['bind','lookup'] def __init__(self): self.actors = {} def bind(self, name, actor): print "Se ha registrado ",name self.actors[name] = actor def lookup(self, name): if name in self.actors: return self.actors[name] else: return None if __name__ == "__main__": print "Registry" set_context() host = create_host('http://'+sys.argv[1]+':'+sys.argv[2]+'/') registry = host.spawn('registre', Registry) print 'host '+sys.argv[1]+' listening at port: '+sys.argv[2] serve_forever()
''' Basic remote example sending tell messages. CLIENT @author: Daniel Barcelona Pons ''' from pyactor.context import set_context, create_host, shutdown if __name__ == "__main__": set_context() host = create_host('http://127.0.0.1:1679') e1 = host.lookup_url('http://127.0.0.1:1277/echo1', 'Echo', 's1_server') e1.echo('Hi there!') # TELL message e1.echo('See ya!') shutdown()
#Miramos si el actor esta en el diccionario, si esta devolvemos el actor, si no, nulo def lookup(self, name): if name in self.actors: return self.actors[name] else: return None #Devolvemos todos los actores del diccionario def get_all(self): return self.actors.values() def get_keys(self): return self.actors.keys() if __name__ == "__main__": set_context() ip_registry = str(raw_input("Introdueix la ip del registry: ")) #Creamos un host per crear actors host = create_host('http://' + ip_registry + ':6000/') #Metodo spawn(Nombre,Tipo) registry = host.spawn('regis', Registry) print 'host listening at port 6000' #Metodo para que el host no muera y pueda escuchar las llamadas de otros actores... serve_forever()
from pyactor.context import set_context, create_host, sleep, shutdown class Echo(object): _tell = ['echo', 'bye'] _ask = ['say_something'] def echo(self, msg): print msg def bye(self): print 'bye' def say_something(self): return 'something' if __name__ == "__main__": set_context() h = create_host() e1 = h.spawn('echo1', Echo) e = h.lookup('echo1') print e.say_something() ee = h.lookup_url('local://local:6666/echo1', Echo) print ee.say_something() sleep(1) shutdown()
""" Basic remote example sending ask messages. SERVER @author: Daniel Barcelona Pons """ from pyactor.context import set_context, create_host, serve_forever class Echo(object): _tell = {'echo'} _ask = {'get_msgs'} def __init__(self): self.msgs = [] def echo(self, msg): print(msg) self.msgs.append(msg) def get_msgs(self): return self.msgs if __name__ == '__main__': set_context() host = create_host("http://127.0.0.1:1277/") e1 = host.spawn('echo1', Echo) serve_forever()