def start(root): global STAT screen(root) while True: if not STAT == 0: break resety(root) if STAT == 1: Host.host(root) else: client.client(root)
def main(): args = parse_cmd() setup_env(args) line = sys.stdin.readline().strip() while (line): if (line == "DONE"): print "DONE" break attrib["numHosts"] += 1.0 try: host = Host(line) update_base_metrics(host) check_smiley_vuln(host) output_files(host) output_certs(host) except: sys.stderr.write("*" * 50 + "\n") if (args.verbose): write_error(str(sys.exc_info()[0])) write_error(str(traceback.format_exc())) write_error("A hard-error was encounter for " + \ "IP %s " % json.loads(line)["IP"] + \ "(record not processed)") else: write_error("OnlineProcessing : A surpressed error occurred\n") sys.stderr.write("*" * 50 + "\n") attrib["unProcHandle"].write(line + "\n") line = sys.stdin.readline().strip() close_env(args)
def onButtonAdd(self, evt): ip = self.ipValue.GetValue() mac = self.macValue.GetValue() name = self.nameValue.GetValue() desc = self.descValue.GetValue() ports = self.portsValue.GetValue() live = self.liveValue.GetStringSelection() netbios = self.netBiosValue.GetValue() if self.add: if existHostWithMac(self.parent.hosts, mac) == -1: self.parent.hosts.append( Host(ip, mac, name, desc, ports, live, netbios, False)) wx.MessageBox('Dodano do listy.', 'Info', wx.OK | wx.ICON_INFORMATION) self.Destroy() else: wx.MessageBox( 'Nie można dodać hosta o podanym adresie MAC ponieważ już taki istnieje, nr: ' + str(existHostWithMac(self.parent.hosts, mac)) + '.', 'Info', wx.OK | wx.ICON_INFORMATION) else: self.parent.hosts[self.selected].ip = ip self.parent.hosts[self.selected].mac = mac self.parent.hosts[self.selected].name = name self.parent.hosts[self.selected].desc = desc self.parent.hosts[self.selected].ports = ports self.parent.hosts[self.selected].netbios = netbios self.parent.fillHostList()
def listExecutions(self): for execution in self.db.listExecutions(): execution_l = list(execution) execution_l[1] = Host.Host((execution[1], execution[1], None)) execution_l[4] = execution[4].split('\n') execution_l[5] = execution[5].split('\n') print(Execution.Execution(execution_l))
def get_host_info(self): """ Return a list containing one Host instance for each configured host """ hosts = [] for host in self.get_hosts(): hosts.append(Host.Host(host, self)) return hosts
def getAllHosts(self): hostsResult = self.executor.execute( 'SELECT ip, mac, name, ports, desc, netbios FROM host') hosts = [] for host in hostsResult: hosts.append( Host(host[0], host[1], host[2], host[4], host[3], "Nie", host[5], True)) return hosts
def __init__(self, log_flag): ## Logger object for formatting and printing logs self.logger = Logger(log_flag, LOG_FILE) self.logger.info('Started Domoleaf Slave daemon') ## Array of master daemon on local network self.connected_masters = {} ## Array of monitor KNX on local network self.connected_knx = [] ## Array of monitor EnOcean on local network self.connected_enocean = [] ## Array of cron running on the system self.connected_cron = [] self._scanner = Scanner(log_flag) self._hostlist = [] myhostname = socket.gethostname().upper() if SLAVE_NAME_PREFIX in myhostname: self._scanner.scan() self._hostlist = self._scanner._HostList else: self._hostlist.append(Host('', '127.0.0.1', myhostname)) self._parser = DaemonConfigParser(SLAVE_CONF_FILE) ## Keys for encrypting communications self.encrypt_keys = {} ## Main socket for communication with KNX daemon self.knx_sock = None ## Main socket for communication with master daemon self.master_sock = None ## Main socket for communication with enocean daemon self.enocean_sock = None ## Main socket for communication with cron self.cron_sock = None ## Private AES key got from configuration file self.private_aes = self._parser.getValueFromSection( 'personnal_key', 'aes') self.wifi_init(self._parser.getValueFromSection('wifi', 'ssid'), self._parser.getValueFromSection('wifi', 'password'), self._parser.getValueFromSection('wifi', 'encryption'), self._parser.getValueFromSection('wifi', 'mode'), 0) ## Port on which connect got from configuration file self.connect_port = self._parser.getValueFromSection( SLAVE_CONF_CONNECT_SECTION, SLAVE_CONF_CONNECT_PORT_ENTRY) ## Callback array indexed on packet type self.functions = { KNX_READ_REQUEST: self.knx_read_request, KNX_WRITE_SHORT: self.knx_write_short, KNX_WRITE_LONG: self.knx_write_long, KNX_WRITE_TEMP: self.knx_write_temp, CHECK_SLAVE: self.check_slave, MONITOR_IP: self.monitor_ip, DATA_UPDATE: self.update, SEND_TECH: self.send_tech, SEND_ALIVE: self.send_alive, SEND_INTERFACES: self.send_interfaces, SHUTDOWN_D3: self.shutdown_d3, REBOOT_D3: self.reboot_d3, WIFI_UPDATE: self.wifi_update }
def initializeDB(self, metadata, engine): taskInfos = TaskInfo.dbDesign(metadata) inputFiles = InputFile.dbDesign(metadata) outputFiles = OutputFile.dbDesign(metadata) arguments = Argument.dbDesign(metadata) gridTasks = GridTask.dbDesign(metadata) hosts = Host.dbDesign(metadata) taskGroups = TaskGroup.dbDesign(metadata) metadata.create_all(engine)
def obtainTaskHost(self, dbSession, gwTaskID): hostname = Host.readHost(self.gwpsFileLocation, gwTaskID) auxHost = dbSession.query(Host.Host).filter(Host.Host.hostname == hostname).first() if (auxHost == None): print("new host employed! " + hostname) auxHost = Host.Host(hostname) dbSession.add(auxHost) dbSession.commit() return auxHost
def __init__(self, xml_input): '''constructor function, need a xml file name as the argument''' try: self.__dom = xml.dom.minidom.parse(xml_input) self.__session = None self.__hosts = {} for host_node in self.__dom.getElementsByTagName('host'): __host = Host.Host(host_node) self.__hosts[__host.ip] = __host except Exception as ex: print "\t[-] Parser error! Invalid nmap file!" #logging.error(ex) raise
def arping(ip_range, timeout=2): """Returns a list of alive Host in the specified ip_range. @param ip_range an range of ip (ex : 192.168.1.*, 192.168.1.2-254). @param timeout the timeout of the arp paquets. @return the list of alive host found in the specified subnet.""" ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip_range), timeout=timeout) hosts = [] for req, res in ans: ip = res.getlayer(ARP).psrc mac = res.getlayer(Ether).src name = resolve_host_name(ip) # try to get the host name. hosts.append(Host(ip, mac, name)) return hosts
def runHost(self): # ip, port = addGame() # get ip - if cannot determine, manual input; also get port hostip = getOwnIP() if hostip == GameWindow.NO_ADDR: hostip = self.getInfo(self.wid, 70, "Host ip:") hostport = self.getInfo(self.wid, 70, "Host port:") # verify before connect if re.match(IP_REG, hostip) and re.match(PORT_REG, hostport): hostport = int(hostport) try: host = Host(hostip, hostport) except socket.error: return self.runClient(host) else: print "Error: Not a valid host port"
def __init__(self, FileName): '''constructor function, need a xml file name as the argument''' try: self.__dom = xml.dom.minidom.parse(FileName) except IOError: print "IO error, open " + FileName + " error" sys.exit() except: print "parse " + FileName + " error" sys.exit() self.__session = None self.__hosts = {} for host_node in self.__dom.getElementsByTagName('host'): __host = Host.Host(host_node) self.__hosts[__host.ip] = __host
def create_target(access_path, node, host=None): retval = -1 if not isinstance(access_path, int): access_path = get_access_path_id(access_path, host) if not isinstance(node, int): node = Host.get_host_id(node, host) if access_path == -1 or node == -1: print "[Error] The access path or host name/id is invalid." else: cmd = utils.XMS_CLI_HEADER + "target create --access-path {apid} --host {host_id}".format( apid=access_path, host_id=node) ret = utils.execute_cmd_in_host(cmd, host) if ret[2] != 0: print "[Error] Failed to create target. Error message: [{err}]".format( err=ret[1]) else: retval = 0 return retval
def setMitM(self, value): """Active or desactive the MitM attack depending on the specified value.""" if value: self.mitm = True if self.arpThread is None: self.arpThread_stop = threading.Event() self.arpThread = threading.Thread( target=PARPThread, args=(self.host, Host("192.168.1.1", "192.168.1.1", "192.168.1.1"), self.arpThread_stop)) self.arpThread.start() else: self.mitm = False if self.arpThread is not None: self.arpThread_stop.set( ) # note that this doesn't really kill the thread, another method should be used later... self.arpThread = None print("not ARP")
def buildRequest(self): hostUrl = Url(self.__requestURL) requestLine = "{0} {1} HTTP/{2}".format( self.getMethod(), hostUrl.getPath() + hostUrl.getQuery(), self.getHttpVersion()) self.addHeader("Host", hostUrl.getHost()) fullRequest = "{0}\r\n{1}\r\n{2}".format(requestLine, self.getHeaders(), self.getBody()) # print("fullRequest: \r\n" + fullRequest) hostObj = Host(hostUrl.getHost(), hostUrl.getPort(), fullRequest, self.__verbose, self.__outputFilePath) return hostObj
def read_in_hosts(infile): """arg: filename to open out: A list of Host instances description: open infile, read items, create list of Host instances """ try: file_handle = open(infile) file_lines = file_handle.readlines() file_handle.close() except IOError: #TODO Take into account curses... print("Error opening %s" % infile) exit(1) host_list = [] for line in file_lines: #Split the line by whitespace, and verify it's not a comment if (line.strip()[0] != '#'): line_items = line.split() host_list.append( Host.Host(line_items[0].strip(), line_items[1].strip())) return host_list
def pingAddr(self, addresses): hosts = [] remaining = len(addresses) queue = Queue(remaining) self.logger.log( 'Processing {} addresses in batches of {}.'.format( remaining, str(self.configuration['ping_chunk_size'])), 0) batch_index = 1 start = time() try: for chunk in chunks(addresses, self.configuration['ping_chunk_size']): remaining -= len(chunk) first = chunk[0] last = chunk[-1:][0] self.logger.log( 'Batch #{:03d} ({}) {} → {}, ({} left)'.format( batch_index, str(len(chunk)), first, last, str(remaining)), 0) for address in chunk: host = Host.Host() Process(target=host.process, args=(address, queue)).start() for host in chunk: hosts.append(queue.get()) batch_index += 1 end = time() elapsed = str(timedelta(seconds=(end - start))) rate = len(addresses) / (end - start) self.logger.log( '{} addresses scanned in {} ({:.2f} a/s)'.format( len(addresses), elapsed, rate), 0) except KeyboardInterrupt: self.logger.log('Host update cancelled by keyboard interrupt!', 5) return hosts
def getNetworkHosts(self, ip, netmask, myMac): allHosts = [] nm = self.nm nm.scan(hosts=ip + '/' + str(netmask), arguments='-n -sP -PE -PA21,23,80,3389') print ip + '/' + str(netmask) for ipAddress in nm.all_hosts(): print nm[ipAddress] ip = ipAddress remote = True try: if str(nm[ipAddress]['status']['reason']).startswith('local'): remote = False except: pass try: mac = nm[ipAddress]['addresses']['mac'] except: mac = "" desc = "" ports = "" netbios = "" live = "Tak" try: name = nm[ipAddress]['vendor'][str(mac)] except: name = "" if remote == False: mac = myMac allHosts.append( Host(ip, mac, name, desc, ports, live, netbios, remote)) return allHosts
def addNewHost(self, macAddr, ipAddr, hostname): self._HostList.append(Host(macAddr, ipAddr, hostname.upper(), None, 0))
def processHost(self, hostname): host = Host.Host(hostname, self.configuration, self.logger) return host.Process()
(o, a) = opts[0] if o in ("-r", "--resource"): if len(sys.argv) <= 2: setupScreen() import ResourceControl r = ResourceControl.ResourceControl(ovtDB) exitcode = r.run(sys.argv[2:]) sys.exit(exitcode) elif o in ("-p", "--prepare"): import TestPreparation p = TestPreparation.TestPreparation(ovtDB) p.run(sys.argv[2:]) sys.exit(0) elif o in ("-h", "--host"): import Host n = Host.Host(ovtDB) n.run(sys.argv[2], sys.argv[3:]) sys.exit(0) elif o in ("-g", "--gridhost"): import GridHost n = GridHost.GridHost(ovtDB) n.run(sys.argv[2:]) sys.exit(0) elif o in ("-a", "--allocate"): setupScreen() import HostAllocator a = HostAllocator.HostAllocator(ovtDB) a.run() sys.exit(0) elif o in ("-c", "--check"): setupScreen()
except ValueError: print("Port must be an integer. Try again.") continue #will this work? Yes! break # address = ('localhost', port) #does the first part of address need to be determined after the socket is made? Probably. while not done: try: num_cns = int( input("Number of players? (probably at least 1) ")) except ValueError: print("Number of players must be an integer. Try again.") continue #will this work? break print("Initializing Host") h = Host.Host( "No", WORLD_WIDTH, WORLD_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT, TOP, 0, port, num_cns, FPS ) #I think the issue I was having was leaving out console_lines(the 0) while not h.GAME_OVER: t_1 = time.time() h.update() t_2 = time.time() to_wait = (1.0 / FPS - (t_2 - t_1)) # if to_wait > 0: # print("waited") time.sleep(max(to_wait, 0)) # elif h_or_c == "client" or h_or_c == "Client": elif h_or_c.lower() == "client": c = Client.Client("Asteroids Arena", WORLD_WIDTH, WORLD_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT, TOP, 0, FPS) #???? There needs to be some way of verifying that a proper connection was formed. #Note: there sort of is: I could use try/except with a ConnectionRefusedError. Maybe a few other errors, too.
def display_jobs(self, parsable=False, hostname=None): """ Create a nicely formatted list of RSV jobs running in Condor-Cron """ job_status = ["U", "I", "R", "X", "C", "H", "E"] def display_metric(classad, parsable): status = job_status[int(classad["JobStatus"])] next_run_time = "UNKNOWN" deferral_time = 0 try: probe_interval = int(classad['OSGRSVProbeInterval']) deferral_time = int(classad['EnteredCurrentStatus']) + probe_interval except (KeyError, TypeError, ValueError): try: deferral_time = int(classad['DeferralTime']) except (KeyError, TypeError, ValueError): pass if deferral_time: if parsable: next_run_time = strftime("%Y-%m-%d %H:%M:%S %Z", time.localtime(deferral_time)) else: next_run_time = strftime("%m-%d %H:%M", time.localtime(deferral_time)) metric = "UNKNOWN?" if "OSGRSVMetric" in classad: metric = classad["OSGRSVMetric"].strip('"') owner = classad["Owner"].replace('"', "") if parsable: output = "%s.%s | %s | %s | %s | %s\n" % (classad["ClusterId"], classad["ProcId"], owner, status, next_run_time, metric) else: output = "%5s.%-1s %-10s %-2s %-15s %-44s\n" % (classad["ClusterId"], classad["ProcId"], owner, status, next_run_time, metric) return metric, output # # Build a table of jobs for each host # hosts = {} running_metrics = {} classads = self.get_classads("OSGRSV==\"metrics\"") if not classads: if parsable: self.rsv.echo("ERROR: Condor-cron is running but no RSV metrics are running") else: self.rsv.echo("No metrics are running") else: for classad in classads: host = "UNKNOWN?" if "OSGRSVHost" in classad: host = classad["OSGRSVHost"].strip('"') if hostname and hostname != host: continue if host not in hosts: running_metrics[host] = [] hosts[host] = "Hostname: %s\n" % host if not parsable: hosts[host] += "%7s %-10s %-2s %-15s %-44s\n" % \ ("ID", "OWNER", "ST", "NEXT RUN TIME", "METRIC") (metric, text) = display_metric(classad, parsable) running_metrics[host].append(metric) hosts[host] += text # Add in any hosts that have ALL their metric missing for host in self.rsv.get_hosts(): if host not in hosts: hosts[host] = "Hostname: %s\n\tThis host has no running metrics.\n" % host running_metrics[host] = [] self.rsv.echo("") # get a newline to separate output from command for host in hosts: self.rsv.echo(hosts[host]) # Determine if any metrics are enabled on this host, but not running missing_metrics = [] enabled_metrics = Host.Host(host, self.rsv).get_enabled_metrics() for metric in enabled_metrics: if metric not in running_metrics[host]: missing_metrics.append(metric) if missing_metrics: if parsable: self.rsv.echo("MISSING: " + " | ".join(missing_metrics)) else: self.rsv.echo("WARNING: The following metrics are enabled for this host but not running:\n%s\n" % " ".join(missing_metrics)) # # Show the consumers also if a specific hostname was not requested # if not hostname and not parsable: classads = self.get_classads("OSGRSV==\"consumers\"") running_consumers = [] if not classads: self.rsv.echo("No consumers are running") else: self.rsv.echo("%7s %-10s %-2s %-30s" % ("ID", "OWNER", "ST", "CONSUMER")) for classad in classads: status = job_status[int(classad["JobStatus"])] owner = classad["Owner"].replace('"', "") consumer = classad["OSGRSVUniqueName"].replace('"', "") running_consumers.append(consumer) self.rsv.echo("%5s.%-1s %-10s %-2s %-30s" % (classad["ClusterId"], classad["ProcId"], owner, status, consumer)) # Display a warning if any consumers are enabled but not running enabled_consumers = self.rsv.get_enabled_consumers() missing_consumers = [] for consumer in enabled_consumers: if consumer.name not in running_consumers: missing_consumers.append(consumer.name) if missing_consumers: self.rsv.echo("\nWARNING: The following consumers are enabled but not running:\n%s\n" % " ".join(missing_consumers)) return True
h.run_command_chk_rc("service vgcd start") h.mount_fs(device, mnt_pnt) md5sum_f = h.get_md5sum(file) if md5sum_f == md5sum_s: print "SUCCESS: md5sum before '%s' matches after '%s' at restart '%i'" % ( md5sum_s, md5sum_f, c) print " " continue else: print "FAIL: md5sum before '%s'doesn't matches after '%s' at restart '%i'" % ( md5sum_s, md5sum_f, c) sys.exit(1) h = Host(sys.argv[1]) device = sys.argv[2] # /dev/vgca0 mnt_pnt = "/flash-max" #fs = sys.argv[2] try: h.umount_fs(device) #except CommandError: # sys.exit(1) except: print "INFO: Seems like it is filesystem is already unmounted continuing.." pass #filesystems = ['ext2','ext3', 'ext4' , 'xfs'] #filesystems = ['ext3', 'ext4' , 'xfs'] filesystems = ['xfs'] for fs in filesystems:
import Host import Player import Game import Worker worker = Worker.Worker() player = Player.Player('Neo', worker) host = Host.Host('Amitabh Bachchan', worker) host.getCards('movies.txt') game = Game.Game(worker) game.addHost(host) game.addPlayer(player) game.start()
def parseRoomXML(self, xml): self.w, self.h = map(int, [xml.get('width'), xml.get('height')]) for obj in xml: # Iterate through room objects attr = obj.attrib x, y = int(attr["x"]), int(attr["y"]) if obj.tag == "spawn": typ = int(obj[0].get('type')) var = int(obj[0].get('variant')) subtype = int(obj[0].get('subtype')) # Spawn the correct item for the type if typ in [1500, -1, -1, 1496, -1]: self.poops.append( Poop([1500, -1, -1, 1496, -1].index(typ), (x, y), self.textures["poops"], self.sounds["pop"])) elif typ == 1000: self.rocks.append( Rock(randint(0, 2), (x, y), False, self.sounds["rockBreak"], self.textures["rocks"])) elif typ == 33: self.fires.append( Fire(0, (x, y), [self.sounds["fireBurn"], self.sounds["steam"]], self.textures["fires"])) elif typ == 5 and var == 10: self.other.append( Heart( [1, 3, 6].index(subtype), (x, y), [self.sounds["heartIntake"], self.sounds["holy"]], self.textures["pickupHearts"])) elif typ == 5 and var == 20: self.other.append( Coin(subtype - 1, (x, y), [ self.sounds["coinDrop"], self.sounds["coinPickup"] ], self.textures["coins"])) elif typ == 5 and var == 30: self.other.append( Key(0, (x, y), [self.sounds["keyDrop"], self.sounds["keyPickup"]], self.textures["keys"])) elif typ == 5 and var == 40: self.other.append( Bomb(self, 0, (x, y), [self.sounds["explosion"]], self.textures["bombs"], explode=False)) elif typ == 13: self.enemies.append( Fly((x, y), [self.sounds["deathBurst"]], self.textures["enemies"]["fly"])) elif typ == 14: self.enemies.append( Pooter((x, y), [self.sounds["deathBurst"]], self.textures["enemies"]["pooter"])) elif typ == 26: self.enemies.append( Maw((x, y), [self.sounds["deathBurst"]], self.textures["enemies"]["maw"])) elif typ == 27: self.enemies.append( Host((x, y), self.sounds, self.textures)) elif typ == 30: self.enemies.append( Boil((x, y), self.sounds, self.textures))
# lambd = 5 # for i in range(4): # host.append(Host.Host(chr(ord('A')+i), float(lambd) / slot_time)) # router.append(Router.Router("R"+str(i+1))) # # max_time = int(input("Enter the max time: ")) # part3 = WAN(host, router, slot_time) # for _ in range(max_time + 1): # part3.run() # time.sleep(3) # # part3.print_stat() host = [] router = [] slot_time = 200 #15 lambd = 1 #5 for i in range(4): host.append(Host.Host(chr(ord('A') + i), float(lambd) / slot_time)) router.append(Router.Router("R" + str(i + 1))) part3 = WAN(host, router, slot_time) # for i in range(3000000-1): # part3.run() def runCodeRun(): global part3 part3.run() return part3 # part3.print_stat()
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os sys.path.append(os.path.abspath('./Modules/')) import Host, Apache2, DevNux Host = Host() Apache2 = Apache2() DevNux = DevNux() def index_in_list(a_list, index): if(index < len(a_list)): return True return False # CASO PASSE ARGUMENTOS. # python3 main.py dominio.local /home/path/do/dominio if(index_in_list(sys.argv, 1) and index_in_list(sys.argv, 2) and sys.argv[1] != '' and sys.argv[2]): #print('Informe o domínio') domain = sys.argv[1] #print('Informe o diretório do projeto') diretorio = sys.argv[2] # Host-Virtual res = Apache2.add(domain, diretorio)
def dispatcher(rsv, action, options, jobs=None): """ Handle on, off, enable, disable. Determine if jobs are metrics or consumers. """ condor = Condor.Condor(rsv) hostname = None if options and options.host: hostname = options.host if action == "start" or action == "stop": if not condor.is_condor_running(): rsv.echo("ERROR: condor-cron is not running.") return False # If we are given a hostname but no list of jobs, assume that we want to act # on all jobs that are enabled for that host. This only applies to starting # and stopping, but not to enabling and disabling (since we couldn't know the # metric list in those cases) if action in ('start', 'stop') and hostname and not jobs: host = Host.Host(hostname, rsv) jobs = host.get_enabled_metrics() # # If we are not passed specific jobs to start, start all metrics and consumers # if not jobs: if action == "start": return start_all_jobs(rsv, condor) elif action == "stop": return stop_all_jobs(rsv, condor) elif action == "enable": rsv.echo("ERROR: You must supply metrics/consumers to enable") return False elif action == "disable": rsv.echo("ERROR: You must supply metrics/consumers to disable") return False # # If we are passed a list of specific metrics/consumers, determine whether each # item in the list is a metric or consumer, and send to the appropriate function # else: # Since a user can input either metric of consumer names we need to get a list # of the installed metrics and consumers and check which category each job is in. available_metrics = rsv.get_installed_metrics() available_consumers = rsv.get_installed_consumers() host = None if hostname: host = Host.Host(hostname, rsv) num_errors = 0 write_config_file = False for job in jobs: is_metric = job in available_metrics is_consumer = job in available_consumers if is_metric and is_consumer: rsv.log("WARNING", "Both a metric and a consumer are installed with the name '%s'. " + "Not starting either one" % job) num_errors += 1 elif not is_metric and not is_consumer: rsv.log("WARNING", "Supplied job '%s' is not an installed metric or consumer" % job) num_errors += 1 elif is_metric: if not host: rsv.log("ERROR", "When passing specific metrics you must also specify a host.") num_errors += 1 continue metric = Metric.Metric(job, rsv, hostname) if action == "start": num_errors += start_metric(rsv, condor, metric, host) elif action == "stop": num_errors += stop_metric(rsv, condor, metric, host) elif action == "enable": write_config_file |= enable_metric(rsv, metric, host, options.knobs) elif action == "disable": write_config_file |= disable_metric(rsv, metric, host) elif action == "show-config": show_config_metric(rsv, metric) elif is_consumer: consumer = Consumer.Consumer(job, rsv) if action == "start": num_errors += start_consumer(rsv, condor, consumer) elif action == "stop": num_errors += stop_consumer(rsv, condor, consumer) elif action == "enable": enable_consumer(rsv, consumer) elif action == "disable": disable_consumer(rsv, consumer) elif action == "show-config": show_config_consumer(rsv, consumer) if write_config_file: host.write_config_file() if action == "enable": rsv.echo("\nOne or more metrics have been enabled and will be started the next time RSV is started. To turn them on immediately run 'rsv-control --on'.") elif action == "disable": rsv.echo("\nOne or more metrics have been disabled and will not start the next time RSV is started. You may still need to turn them off if they are currently running.") if num_errors > 0: actions = {"start" : "starting", "stop" : "stopping", "enable" : "enabling", "disable" : "disabling", "show-config" : "displaying configuration for" } plural = "" if len(jobs) > 1: plural = "s" rsv.log("ERROR", "Problem %s %s job%s." % (actions[action], num_errors, plural)) return False else: return True
def do_connect(self, argsString): args = shlex.split(argsString) host = Host.Host(*args) self.host = host self.SetPrompt()