def get_proxy_without_uri(self, obj, passw=None): target = obj.split(".") if (target[0] and target[1] and target[0].count("*") == 0 and target[1].count("*") == 0): if passw is None: passw = target[0] try: Pyro4.config.BROADCAST_ADDRS = self.broadcast_ns ns = Pyro4.locateNS() proxy = utils.get_pyro4proxy(ns.lookup(target[0]), passw) bot_uris = proxy.get_uris() for x in bot_uris: (name, ip, port) = utils.uri_split(x) if name.split(".")[1] == target[1]: proxy = utils.get_pyro4proxy(x, passw) return proxy except Exception: # print "Error al resolver ", obj raise else: if self.usingBB: # TODO: var ns is not initialized here ns.proxy(target, passw) else: print( colored( "--- Para usar esta funcionalidad se necesita de BigBrother ---", "red")) return None return None
def add_resolved_remote_dep(self, dep): # print(colored("New remote dep! {}, type: {}".format(dep, type(dep)), "green")) if isinstance(dep, dict): k = list(dep.keys())[0] proxy_lst = [] try: if isinstance(dep[k], list): for u in dep[k]: if u not in self._resolved_remote_deps: (name, _, _) = utils.uri_split(u) proxy_lst.append( utils.get_pyro4proxy(u, name.split(".")[0])) self._resolved_remote_deps.append(u) if k in self.deps and isinstance(self.deps[k], list): self.deps[k].extend(proxy_lst) else: self.deps[k] = proxy_lst else: if dep[k] not in self._resolved_remote_deps: (name, _, _) = utils.uri_split(dep[k]) self.deps[k] = utils.get_pyro4proxy( dep[k], name.split(".")[0]) self._resolved_remote_deps.append(dep[k]) if self._unr_remote_deps is not None: if k in self._unr_remote_deps: self._unr_remote_deps.remove(k) except Exception as ex: template = "[control.add_resolved_remote_dep()] An exception of type {0} occurred. Arguments:\n{1!r}" print(template.format(type(ex).__name__, ex.args)) self.check_remote_deps() else: print("Error in control.add_resolved_remote_dep(): No dict", dep)
def _get_proxys(self): proxys = [x for x in self.robot.get_uris(True) if isinstance(x, str)] for p in proxys: con = p.split("@")[0].split(".")[1] name = p.split("@")[0].split(".")[0].split(":")[1] proxy = utils.get_pyro4proxy(p, name) setattr(self, con, proxy)
def get_ns(self): if self.nameserver is None: default_ns = Pyro4.config.BROADCAST_ADDRS # Looking for Network NameServer for x in utils.get_all_ip_address(broadcast=True): if (self.nameserver): break try: Pyro4.config.BROADCAST_ADDRS = x self.broadcast_ns = x self.nameserver = Pyro4.locateNS() self.nameserver.ping() printInfo("NameServer located.") except Exception: self.nameserver = None if (self.nameserver): # ¿BigBrother or Random NS? try: ns_uri = self.nameserver.lookup("bigbrother") possible_ns = utils.get_pyro4proxy(ns_uri, ROUTER_PASSWORD) if (possible_ns.ready()): self.ns_uri = ns_uri self.nameserver = possible_ns printInfo("[NS_Type] BigBrother ----> %s" % self.ns_uri) self.usingBB = True except Pyro4.errors.NamingError: printInfo("[NS_Type] Generic NameServer ----> %s" % self.nameserver.lookup("Pyro.NameServer")) if self.nameserver is None: printInfo("NameServer not found.", "red") # Creating a NameServer try: port = utils.get_free_port(self.port_ns, ip=self.ip) Pyro4.config.SERIALIZERS_ACCEPTED = ["json", "marshal", "serpent", "pickle"] self.nsThread = threading.Thread( target=nm.startNSloop, kwargs={'host': self.ip, 'port': port}) self.nsThread.start() time.sleep(1) printInfo("NameServer created.") except Exception: printInfo("Error creating NameServer", "red") self.nameserver = None # Locate NS attempts = 0 while attempts < 10: try: Pyro4.config.BROADCAST_ADDRS = default_ns self.nameserver = Pyro4.locateNS() self.nameserver.ping() break except Exception: attempts += 1 time.sleep(0.3) return self.nameserver if self.nameserver else None
def pre_start_pyro4bot_object(self, name, obj): """Pre starter for component.""" serv_pipe, client_pipe = Pipe() attemps = 5 if "_locals" not in obj: obj["_locals"] = [] if "_resolved_remote_deps" not in obj: obj["_resolved_remote_deps"] = [] if name not in self.PROCESS: self.PROCESS[name] = [] obj["pyro4id"] = self.URI_proxy.new_uri(name, obj["mode"]) obj["name"] = name obj["node"] = self.uri_node obj["uriresolver"] = self.URI_uri obj["tty_out"] = self.node["tty_out"] obj["tty_err"] = self.node["tty_err"] obj["tty_node"] = utils.get_tty() self.PROCESS[name].append(obj["pyro4id"]) self.PROCESS[name].append( Process(name=name, target=self.start_pyro4bot_object, args=(obj, client_pipe))) self.PROCESS[name][1].start() self.PROCESS[name].append(self.PROCESS[name][1].pid) self.PROCESS[name].append(obj["_REMOTE_STATUS"]) status = serv_pipe.recv() status = "FAIL" while attemps > 0: try: pxy = utils.get_pyro4proxy(obj["pyro4id"], self.node["name"]) status = pxy.get_status() break except Exception: attemps -= 1 time.sleep(1) if status == "OK": st = colored(status, 'green') self.PROCESS[name].append(pxy.__docstring__()) if status == "FAIL": st = colored(status, 'red') if status == "WAITING": st = colored(status, 'yellow') if status == "ASYNC": print( "\t\t[%s] STARTING %s --> remotes dependencies in asynchronous mode with --> %s" % (colored(status, 'yellow'), name, colored(' '.join(obj["_unr_remote_deps"]), 'yellow'))) else: print("\t\t[%s] STARTING %s" % (st, obj["pyro4id"])) else: print("ERROR: " + name + " is running")
def __init__(self, name, uri, pid=None): self.exit = True self.robot = utils.get_pyro4proxy(uri, name) self.name = name setattr(self, name, self.robot) self.uri = uri self.pid = pid self.TTY = utils.get_tty() self._get_proxys() self.methods = get_methods(Terminal) self._all_methods = [] self._indexing_methods_() self._control()
def print_process(self, onlyChanges=False): for k, v in self.PROCESS.items(): # Update status try: old_status = v[3] v[3] = utils.get_pyro4proxy(v[0], self.node["name"]).get_status() except Exception: v[3] = "FAIL" if (onlyChanges and v[3] != old_status) or not onlyChanges: if v[3] == "OK": st = colored(v[3], 'green') elif v[3] == "FAIL": st = colored(v[3], 'red') elif v[3] == "WAITING" or v[3] == "ASYNC": st = colored(v[3], 'yellow') print("[{}]\t{} {}".format(st, str(v[2]), str(v[0]).rjust(60, ".")))
def wait_resolv_remotes(self, name, claimant, trys=10, passw=None): bot_uri = None target = name.split(".") if not self.nameserver: return "ERROR", "NOT-NS" if passw is None: passw = target[0] while (bot_uri is None) and (trys > -1): if self.usingBB: try: self.nameserver.request(name, claimant) return "ASYNC", None # BIG BROTHER RULES except Exception: print( "ERROR: Wait_resolv_resolved_remote_deps with bigbrother" ) else: # Trying to resolv without bigbrother if (target[0] and target[1] and target[0].count("*") == 0 and target[1].count("*") == 0): # robot.comp try: bot_uri = Pyro4.locateNS().lookup(target[0]) bot_proxy = utils.get_pyro4proxy(bot_uri, passw) if bot_proxy: remoteuri, status = bot_proxy.get_name_uri(name) if remoteuri is not None and status == "OK": return "SYNC", remoteuri # Remote robot OK, comp OK. else: return "WAIT", None # Remote robot OK, comp NOT OK. except Exception: pass else: # Another thing print( colored( "--- Para usar esta funcionalidad se necesita de BigBrother ---", "red")) return "ERROR", "BIG-BROTHER" # big brother needed trys -= 1 time.sleep(0.5) if trys < 0: return "ERROR", name # Remote robot NOT OK
def wait_local_available(self, uri, password, trys=20): # eso puede ser asinc return connect = False if uri.find("@") == -1: uri = self.get_uri(uri) try: p = utils.get_pyro4proxy(uri, password) except Exception: return None while not connect and trys > 0: trys = trys - 1 try: connect = p._pyroHandshake == "hello" except Exception: connect = False time.sleep(0.2) if connect: return uri else: return None
def get_proxy(self, obj, passw=None): if isinstance(obj, basestring): obj = [obj] if (self.get_ns()): for d in obj: try: if (d.count('PYRO:') == 1 and d.count('@') == 1 and d.count(":") == 2 and d.count(".") in range(3, 5)): (name, _, _) = utils.uri_split(d) if ("." in name): name = name.split(".")[0] if (passw is None): passw = name return utils.get_pyro4proxy(d, passw) elif (d.count(".") == 1): # simplebot.component return (self.get_proxy_without_uri(d, passw)) else: print "Objeto no valido" except Exception: return None
from node.libs import utils import time from termcolor import colored if __name__ == "__main__": try: if len(sys.argv) != 2: print("File was expected as argument.") os._exit(0) else: jsonbot = sys.argv[1] PROCESS = robot.starter(filename=jsonbot) setproctitle.setproctitle("PYRO4BOT." + PROCESS[0] + "." + "Console") ROB = utils.get_pyro4proxy(PROCESS[1], PROCESS[0]) salir = True time.sleep(2) while salir: print( colored( "\n----\nAvailable commands:: \n* Doc \n* Status \n* Exit\n----\n", "green")) cad = input("{} ".format(colored(PROCESS[0] + ":", 'green'))) if cad.upper() == "EXIT": ROB.shutdown() os.kill(PROCESS[3], 9) exit() if cad.upper() == "STATUS": ROB.print_process()