def test_init_and_basic_simulation (self): e = event_simulator.Event_Simulator({"h1":host.Host("h1",["l1"]),\ "h2":host.Host("h2",["l1"]),\ "f1":flow.Data_Source("f1", "h1", "h2", 20, 1)}) self.assertEqual(e.get_current_time(), 0.0) self.assertFalse(e.are_flows_done()) self.assertEqual(e.get_element("h1").get_id(), "h1") self.assertEqual(e.get_element("h2").get_id(), "h2") self.assertEqual(e.get_element("f1").get_id(), "f1") e.request_event(event.Event().set_completion_time(1.0)) e.request_event(event.Event().set_completion_time(2.0)) e.request_event(event.Event().set_completion_time(0.5)) e.request_event(event.Event().set_completion_time(1.5)) e.request_event(event.Event().set_completion_time(0.2)) ''' Now event heap should be ordered 0.2, 0.5, 1, 1.5, 2 ''' e.run_next_event() self.assertEqual(e.get_current_time(), 0.2) e.run_next_event() self.assertEqual(e.get_current_time(), 0.5) e.run_next_event() self.assertEqual(e.get_current_time(), 1.0) e.run_next_event() self.assertEqual(e.get_current_time(), 1.5) e.run_next_event() self.assertEqual(e.get_current_time(), 2.0)
def test_init(self): ID = "H1" Links = ["L1"] h = host.Host(ID,Links) h.log("Hello World!") self.assertEqual(h.get_id(), ID) with self.assertRaises(ValueError): h2 = host.Host(ID,["L1","L2"])
def SpawnHost(self, Group=None, Account=None): self.Debug('INFO', "Spawn Host (" + str(Group) + "/" + str(Account) + ")") if Group: GroupRange = [Group] else: GroupRange = self.Config['Groups'].keys() if Account: AccountRange = [Account] else: AccountRange = [] for Group in GroupRange: for Account in self.Config['GroupUsers'][Group].keys(): AccountRange.append(Account) AccountRange.sort() for Group in GroupRange: if self.Config['Groups'].has_key(Group): for Account in AccountRange: if self.Config['GroupUsers'][Group].has_key(Account): Config = self.Config['Groups'][Group] for Key in Config.keys(): if self.Config['GroupUsers'][Group][ Account].has_key(Key): Config[Key] = self.Config['GroupUsers'][Group][ Account][Key] self.Hosts[Account] = host.Host( Account, Group, self, Config, self.Config['GroupUsers'][Group][Account]) self.Hosts[Account].start() break # only spawn one host for each group
def __init__(self, a): """ Initialize the Scan tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT """ # sanity check assert (isinstance(a, agent.Agent)) # save the agent reference self.a = a self.a.tc_h1("SCAN TESTS") # create the host instance self.host = host.Host(a, STA) # create the access point instances self.ap1 = accesspoint.AccessPoint(a, AP1, channel=5, period=100, ssid="louis") self.ap2 = accesspoint.AccessPoint(a, AP2, channel=8, period=99, ssid="steven") # reset the host (resetting the MIBs) self.host.reset(True) # set the host MAC address self.host.dbg_macaddr()
def __init__(self, a): """ Initializes the TX tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT """ # sanity check assert (isinstance(a, agent.Agent)) # save the agent reference self.a = a self.a.tc_h1("TX TESTS") # create the host instance self.host = host.Host(a, STA) # create the access point instance self.ap = accesspoint.AccessPoint(a, AP) # reset the host without resetting the MIBs self.host.reset(False) # open the path for the AP and configure the mode as ESS STA self.host.dbg_add(self.ap.macaddr, 1)
def parse_hosts(f, l_map): hosts = [] h_map = {} num_hosts = next_line(f, 'i') for i in xrange(num_hosts): addr = next_line(f) link_id = next_line(f) # Get the link object with that ID from the map host_link = l_map[link_id] host_id = next_line(f) # Construct host object, add it to host map and list h = host_class.Host(host_id, host_link) h_map[host_id] = h hosts.append(h) # Add the host as an 'end' to the link host_link.add_end(h) # Set the map for the host class host_class.Host.h_map = h_map return (hosts, h_map)
def __init__(self, a): """ Initialize the RX tests. Mandatory arguments: a -- test agent object to use to communicate with the DUT """ # sanity check assert (isinstance(a, agent.Agent)) # save the agent reference self.a = a self.a.tc_h1("RX TESTS") # create the host instance self.host = host.Host(a, STA) # create the access point instance self.ap = accesspoint.AccessPoint(a, AP, channel=5, period=100, ssid="louis") # reset the host (resetting the MIBs) self.host.reset(True) # set the host MAC address self.host.dbg_macaddr() # open the data path for the AP and set the STA in ESS self.host.dbg_add(self.ap.macaddr, 1)
def main(portname): """ Starts the Master RS-232 service cmd_table = ''' H or ? to show Help Q or CTRL+C to Quit V - Enable Verbose mode ''' """ #print "Starting RS-232 Master on port {:s}".format(portname) master = host.Host() master.start(portname) # Loop until we are to exit try: #print cmd_table while master.running: cmd = raw_input() result = master.parse_cmd(cmd) if result is 0: pass elif result is 1: master.stop() elif result is 2: print cmd_table except KeyboardInterrupt: master.running = False
def __init__(self, parent=None): super(HostWidget, self).__init__(parent) self.host = host.Host() self.running = True self.start_on = True # set background color p = self.palette() p.setColor(self.backgroundRole(), Qt.white) self.setPalette(p) main_vbox = QVBoxLayout() main_vbox.setMargin(50) main_vbox.addStretch() ## temporary control_hbox = QHBoxLayout() control_hbox.addStretch() measures_label = QLabel("Measures") control_hbox.addWidget(measures_label) measures_up_button = QPushButton("^") measures_down_button = QPushButton("v") measures_up_button.clicked.connect( host.FoxDotHandler.increment_measure) measures_down_button.clicked.connect( host.FoxDotHandler.decrement_measure) control_hbox.addWidget(measures_up_button) control_hbox.addWidget(measures_down_button) reset_button = QPushButton("Reset") reset_button.clicked.connect(self.reset) self.start_stop_button = QPushButton("Stop") self.start_stop_button.clicked.connect(self.toggle_stop) control_hbox.addWidget(reset_button) control_hbox.addWidget(self.start_stop_button) main_vbox.addLayout(control_hbox) ip_hbox = QHBoxLayout() ip_hbox.setAlignment(Qt.AlignCenter) ip_address = self.getIPAddress() ip_label = QLabel("Host IP Address: {}".format(ip_address)) newfont = QFont("Ubuntu", 20, QFont.Bold) ip_label.setFont(newfont) ip_hbox.addWidget(ip_label) main_vbox.addLayout(ip_hbox) self.setLayout(main_vbox) self.setGeometry(200, 100, 700, 700) self.t = threading.Thread(target=self.run_host, args=(ip_address, )) self.t.start()
def _initializeHostFolders(self): """ Initializes all of the hosts with a pub/prv RSA key and initial executable. """ i = 1 success = False for folder in self.hostFolders: if os.path.isdir(folder): #create this hosts initial local exe (just overwrite if it already exists,for testing) hostExePath = folder + "/myExe.exe" f = open(hostExePath, "w+") f.write(self.initialUpdate.Data) f.close() #make the file executable st = os.stat(hostExePath) os.chmod(hostExePath, st.st_mode | stat.S_IEXEC) #create the host's public and private keys pubKeyPath = folder + "/pubKey.pem" prvKeyPath = folder + "/prvKey.pem" self._notary.MakeRSAKeys(pubKeyPath, prvKeyPath) #build this host h = host.Host("127.0.0.1", 5555 + i, i, i, self.contract, prvKeyPath, pubKeyPath, self._pubKeyPath) self.hosts.append(h) success = True else: print("ERROR not a host folder: " + folder) i += 1 return success
def __init__(self, config, router_attrs=None, overrides=None): self.errors = [] self.defaults = defaults.Defaults(config['defaults'], self.errors) self.hosts = map(lambda item: host.Host(item, self.defaults), config['hosts']) self.groups = map(group.Group, config['groups']) self.group_by_name = dict( map(lambda group: (group.name, group), self.groups)) self.networks = map(lambda item: network.Network(item, router_attrs), config['networks']) self.backup_schedule = None def is_group(line): return len(line) == 2 def is_user(line): return len(line) > 2 people = config['people'] self.users = dict((user.nickname, user) for user in map(user.User, filter(is_user, people))) self.user_groups = dict(filter(is_group, people)) if overrides is not None: overrides.apply(self) self.errors.extend(host.check_hosts(self.hosts)) self.errors.extend(group.expand_groups(self.groups, self.hosts)) map(host.Host.clean, self.hosts)
def SpawnHost(self, Group=None, Account=None): self.Debug('INFO', "Spawn Host (" + str(Group) + "/" + str(Account) + ")") if Group: GroupRange = [Group] else: GroupRange = self.Config['Groups'].keys() if Account: AccountRange = [Account] else: AccountRange = [] for Group in GroupRange: for Account in self.Config['GroupUsers'][Group].keys(): AccountRange.append(Account) AccountRange.sort() for Group in GroupRange: if self.Config['Groups'].has_key(Group): for Account in AccountRange: if self.Config['GroupUsers'][Group].has_key( Account) and not self.Hosts.has_key(Account): Config = self.Config['Groups'][Group] for Key in Config.keys(): if self.Config['GroupUsers'][Group][ Account].has_key(Key): Config[Key] = self.Config['GroupUsers'][Group][ Account][Key] AccountKey = Group + '=' + str(Account) self.Hosts[AccountKey] = host.Host( AccountKey, Group, self, Config, self.Config['GroupUsers'][Group][Account]) self.Hosts[AccountKey].start() return ([True, 'Started ' + str(AccountKey)])
def getHost(self): """Return the host this proc is allocated from. @rtype: Host @return: The host this proc is allocated from.""" response = self.stub.GetHost( host_pb2.ProcGetHostRequest(proc=self.data), timeout=Cuebot.Timeout) return host.Host(response.host)
def getHosts(self): """Returns the list of hosts for this allocation. @rtype: list<host> @return: list of hosts """ hostSeq = self.stub.GetHosts( facility_pb2.AllocGetHostsRequest(allocation=self.data), timeout=Cuebot.Timeout).hosts return [host.Host(h) for h in hostSeq.hosts]
def create_hosts_from_conf(config_file='hosts.conf'): Config = ConfigParser.ConfigParser() Config.read(config_file) hosts = [] for section in Config.sections(): options = Config.options(section) x = host.Host(**options) hosts.append(x) return hosts
def readHosts(): # Read hosts.txt file f = open("hosts.txt", 'rb') reader = csv.reader(f) hosts = [] for row in reader: h = host.Host(row) hosts.append(h) f.close() return hosts
def __init__(self, endpoints, cert, ca_cert, interval, items, handlers, defaults): from urlparse import urlparse from jinja2 import Environment env = Environment() self.items = { n: (Template(n, env.from_string(n)), Template(v, env.from_string(v))) for (n, v) in items } self.handlers = { n: (Template(n, env.from_string(n)), Template(v, env.from_string(v))) for (n, v) in handlers } self.interval = interval parsed_endpoints = map(urlparse, endpoints.split(',')) if len(parsed_endpoints) <= 0: raise ValueError("Endpoint parameter is empty or missing") scheme = parsed_endpoints[0].scheme if scheme == "stdout": self.client = StdoutClient() else: self.client = EtcdClient( tuple( map( lambda e: (e.hostname, e.port if e.port else 80 if e.scheme == "http" else 443), parsed_endpoints)), scheme, cert, ca_cert) self.defaults = TemplateDict( {n: Template(v, env.from_string(v)) for (n, v) in defaults}) self.context = Context() import cpu import memory import disk import host import systemd import os_support self.context.add_module(cpu.Cpu()) self.context.add_module(memory.Memory()) self.context.add_module(disk.Disk()) self.context.add_module(host.Host()) self.context.add_module(systemd.Systemd()) self.context.add_module(os_support.OS()) for n in self.handlers: self.client.add_handler(self.context, self.defaults, n, *(self.handlers[n]))
def SpawnHost(self, Group, HostAccount): self.Debug("Spawn Host (" + str(Group) + "/" + str(HostAccount) + ")") if (self.Groups.has_key(Group)): if (self.Hosts.has_key(HostAccount[0])): self.Hosts[HostAccount[0]].HostBattle(Group) else: self.Hosts[HostAccount[0]] = host.Host(self, Group, HostAccount) self.Hosts[HostAccount[0]].start() else: self.Debug("ERROR::Group unknown" + str(Group))
def __init__(self, args=None, names=None): """Init list from LSF or othr host list""" list.__init__(self) if names: for name in names: self.append(modulehost.Host(name)) if args is None: return if type(args) is str: args = [args] self.readhosts(args)
def getActiveHosts(self): print("Scanning for active hosts on subnet " + self.netAddr + "/" + str(self.prefixLen)) suffixLen = 1 << (32 - self.prefixLen) ipRange = self.netAddr + "/" + str(self.prefixLen) activeHosts = [] for result in arping(ipRange, verbose=1)[0].res: ipAddr = result[0].pdst activeHost = host.Host(ipAddr, self.prefixLen, self.subnetMask) activeHosts.append(activeHost) self.activeHosts = activeHosts
def setUp(self): self.hst = host.Host("Yacin", "blue", { 'boardSize': (15, 15), 'maxDots': 100, 'maxPlayers': 4, 'rounds': 1 }) self.client1 = Player("noname", "nocolor", '0.0.0.0') self.client2 = Player("noname", "nocolor", '0.0.0.0') self.client3 = Player("noname", "nocolor", '0.0.0.0') self.client4 = Player("noname", "nocolor", '0.0.0.0') self.client5 = Player("noname", "nocolor", '0.0.0.0')
def get_host_dict_from_csv(self): """ Processing .csv data to dictionary with hosts as key :returns: (dict) host : host object """ logging.info("Processing file: '%s'" % self.file_handler.input_path) res = {} for host_to_append, value_to_append in self.get_valid_row(): for i, host_name in enumerate(host_to_append): try: res[host_name].update(value_to_append[i]) except KeyError: res[host_name] = host.Host(value_to_append[i]) return res
def testHostFields(self): h = host.Host(Active=True, PhysAddress='00:00:00:00:00:00', ip4=['ip4_1', 'ip4_2', 'ip4_3'], ip6=['ip6_1', 'ip6_2', 'ip6_3', 'ip6_4'], DHCPClient='dhcpclient', AssociatedDevice='associated_device', Layer1Interface='l1iface', Layer3Interface='l3iface', HostName='hostname', LeaseTimeRemaining=1000, VendorClassID='vendor_class_id', ClientID='client_id', UserClassID='user_class_id') tr.handle.ValidateExports(h) self.assertEqual(True, h.Active) self.assertEqual('associated_device', h.AssociatedDevice) self.assertEqual('client_id', h.ClientID) self.assertEqual('dhcpclient', h.DHCPClient) self.assertEqual('hostname', h.HostName) self.assertEqual('ip4_1', h.IPAddress) self.assertEqual('ip4_1', h.IP4Address) self.assertEqual('ip6_1', h.IP6Address) self.assertEqual('l1iface', h.Layer1Interface) self.assertEqual('l3iface', h.Layer3Interface) self.assertEqual(1000, h.LeaseTimeRemaining) self.assertEqual('00:00:00:00:00:00', h.PhysAddress) self.assertEqual('user_class_id', h.UserClassID) self.assertEqual('vendor_class_id', h.VendorClassID) self.assertEqual(3, len(h.IPv4AddressList)) self.assertEqual('ip4_1', h.IPv4AddressList['1'].IPAddress) self.assertEqual('ip4_2', h.IPv4AddressList['2'].IPAddress) self.assertEqual('ip4_3', h.IPv4AddressList['3'].IPAddress) tr.handle.ValidateExports(h.IPv4AddressList['1']) tr.handle.ValidateExports(h.IPv4AddressList['2']) tr.handle.ValidateExports(h.IPv4AddressList['3']) self.assertEqual(4, len(h.IPv6AddressList)) self.assertEqual('ip6_1', h.IPv6AddressList['1'].IPAddress) self.assertEqual('ip6_2', h.IPv6AddressList['2'].IPAddress) self.assertEqual('ip6_3', h.IPv6AddressList['3'].IPAddress) self.assertEqual('ip6_4', h.IPv6AddressList['4'].IPAddress) tr.handle.ValidateExports(h.IPv6AddressList['1']) tr.handle.ValidateExports(h.IPv6AddressList['2']) tr.handle.ValidateExports(h.IPv6AddressList['3']) tr.handle.ValidateExports(h.IPv6AddressList['4'])
def main(portname): """ Starts the Master RS-232 service """ cmd_table = ''' H or ? to show Help Q or CTRL+C to Quit V - Enable Verbose mode ''' print "Starting BillAcceptor Master on port {:s}".format(portname) master = host.Host() master.start(portname) sys.stdout.flush() # Loop until we are to exit try: #print cmd_table while master.running: cmd = raw_input() result = master.parse_cmd(cmd) #if result is 0: # pass #elif result is 1: # master.stop() #elif result is 2: # print cmd_table except KeyboardInterrupt: master.running = False print '\n\nGoodbye!' print 'Port {:s} closed'.format(portname) sys.stdout.flush()
def readhosts(self, args): """read hosts from LSF""" p = Popen(["bhosts", "-X", "-w"] + args, stdout=PIPE, stderr=PIPE) out, err = p.communicate() out = out.decode() err = err.decode() for line in out.split("\n")[1:-1]: line = line.split() data = { "HOST": line[0], "HOST_NAME": line[0], "Hostgroup": re.match("(.*?)\d+", line[0]).groups()[0], "STATUS": line[1], "MAX": int(line[3]), "NJOBS": int(line[4]), "RUN": int(line[5]), "SSUSP": int(line[6]), "USUSP": int(line[7]), "RSV": int(line[8]), } if data["HOST"] in Hostlist.allhosts: self.append(Hostlist.allhosts[data["HOST"]]) else: self.append(modulehost.Host(data))
def main(portname): """ Starts the Master RS-232 service """ cmd_table = ''' H or ? to show Help Q or CTRL+C to Quit V - Enable Verbose mode ''' print("Starting RS-232 Master on port {:s}".format(portname)) master = host.Host() master.start(portname) # Loop until we are to exit try: print(cmd_table) while master.running: cmd = input() result = master.parse_cmd(cmd) if result == 0: pass elif result == 1: master.stop() elif result == 2: print(cmd_table) except KeyboardInterrupt: master.running = False print('\n\nGoodbye!') print('Port {:s} closed'.format(portname))
topo = topology.Topology() s1 = switch.Switch("s1") topo.addSwitch(s1) s2 = switch.Switch("s2") topo.addSwitch(s2) s3 = switch.Switch("s3") topo.addSwitch(s3) #s3.chassi=100 s4 = switch.Switch("s4") topo.addSwitch(s4) h1 = host.Host('h1') h1.addPort(port.Port('AA:AA:AA:CC:CC:CC')) h1.addPort(port.Port('AA:AA:AA:AC:CC:CC')) h2 = host.Host('h2') h2.addPort(port.Port('AA:AA:AA:CC:CC:CD')) h3 = host.Host('h3') h3.addPort(port.Port('AA:AA:AA:CC:CC:CE')) h4 = host.Host('h4') h4.addPort(port.Port('AA:AA:AA:CC:CC:CF')) s1.addConnection(4, s3, 1, bandwidth=topology._10M) # Link de 1 Gbps s3.addConnection(1, s1, 4, bandwidth=topology._10M) # Link de 1 Gbps
topo = topology.Topology() central=switch.Switch("central") topo.addSwitch(central) for z in range(10): s1 = switch.Switch("s1") topo.addSwitch(s1) central.addConnection(z,s1,101,topology._100M) s2 = switch.Switch("s2") topo.addSwitch(s2) central.addConnection(100 + z,s2,101,topology._100M) for i in range(100): h=host.Host("h"+str(i)) h.addPort(port.Port('AA:AA:AA:CC:CC:CF')) s1.addConnection(i,h,h.ports[0],topology._100M) for i in range(100): h=host.Host("h"+str(i)) h.addPort(port.Port('AA:AA:AA:CC:CC:CF')) s2.addConnection(i,h,h.ports[0],topology._100M) #print(topo.transferTime(h1, h2, 10 * 1024 * 1024), 'seconds') #p = topo.findpaths(h1,h2,topology._1G) #print(str(p))
print("the timeout (ms): " + sys.argv[2]) arrival_rate = float(sys.argv[3]) print("the arrival rate: " + sys.argv[3]) number_of_host = int(sys.argv[4]) print("number of hosts: " + sys.argv[4]) # statistics transmitted_bytes = 0 total_delay = 0 # initializations hosts = [] arrival_times = [] channel = [] for i in range(number_of_host): hosts.append(host.Host(DEFAULT_DIFS, DEFAULT_SIFS)) arrival_times.append(generate_arrival_time(arrival_rate)) # main for current_time in range(SIMULATION_TIME): channel_is_idle = len(channel) == 0 channel_has_conflict = len(channel) > 1 # schedule data frames for i in range(number_of_host): current_host = hosts[i] arrival_time = arrival_times[i] if arrival_time <= 0: size = generate_frame_size() data_frame = frame.Frame(size, current_time, generate_process_time(size), i, generate_destination(number_of_host),
def webhooks(): print 'Lets go!' # Get the json data json = request.json # parse the message id, person id, person email, and room id message_id = json['data']['id'] person_id = json['data']['personId'] person_email = json['data']['personEmail'] room_id = json['data']['roomId'] apic_person_id = settings.apic_person_id apic_person_email = settings.apic_person_email print message_id # convert the message id into readable text spark = sparkmessages.Message() (message, sender) = spark.get_message(message_id) print 'Message... \n' # message = getmessage.main(message_id) print message # check if the message is the command to get hosts message = message.lower() if message == 'get hosts': apic_host = host.Host() response = apic_host.get_all_hosts() spark.post_message(apic_person_id, apic_person_email, room_id, response) del apic_host elif message.startswith('get host'): name = message.rsplit(None, 1)[-1] apic_host = host.Host() message = apic_host.get_individual_host(name) spark.post_message(apic_person_id, apic_person_email, room_id, message) del apic_host elif message.startswith('get path'): apic_path = path.Path() response = apic_path.path_trace(message) spark.post_message(apic_person_id, apic_person_email, room_id, response) del apic_path elif message.startswith('get network health'): apic_device = device.Device() message = apic_device.get_health_all() spark.post_message(apic_person_id, apic_person_email, room_id, message) del apic_device elif message.startswith('raise'): servicenow.raise_case(message) elif message.startswith('devices in'): location = message.split()[2] print location apic_device = device.Device() response = apic_device.get_devices_location(location) spark.post_message(apic_person_id, apic_person_email, room_id, response) del apic_device else: if sender != settings.apic_person_email: returntext = chatbot.get_response(message) text = returntext.__str__() print 'chatbot response: %s' % text spark.post_message(apic_person_id, apic_person_email, room_id, text) print 'calling output'