当前位置: 首页>>代码示例>>Python>>正文


Python host.Host类代码示例

本文整理汇总了Python中host.Host的典型用法代码示例。如果您正苦于以下问题:Python Host类的具体用法?Python Host怎么用?Python Host使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Host类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: processMessage

 def processMessage(self, msg, fromAddr):
     '''processes the received messages'''
     if isinstance(msg, message.HeloMessage):
         # set your own ip if you dont know it
         if self.ip == "null":
             self.ip = msg.recipientIP
             self.key = Host.constructKey(self.ip, self.port)
             logging.info("You're now connected to a Hachat-network. Your key is " + self.key)
         
         senderIP = fromAddr[0]
         key = Host.constructKey(senderIP, msg.senderPort)
         logging.debug("received: HELO from " + str(key))
         
         if key in self.hosts:
              # if you know Host set status that Host had contact
             host = self.hosts[key]
             host.lastSeen = 1 
             logging.debug(key + " already in hostlist - refreshing lastSeen")
         else: 
             # add new host to hostlist
             self.addToHosts(key)
     
     # only accept Messages from Peers in self.hosts        
     else:
         try:
             sender = msg.origin
         except Exception, e:
             logging.debug("Msg needs origin, but doesn't have one " + str(msg))
             
         try:
             # overriding sender with lastHop
             sender = msg.lastHop
         except Exception, e:
             pass
开发者ID:t2d,项目名称:hachat,代码行数:34,代码来源:peer.py

示例2: TestCases

class TestCases(unittest.TestCase):
    def setUp(self):
        self.localhost_ip        = Host(ip="127.54.78.124")
        self.localhost_hostname  = Host(hostname="localhost")
        self.remotehost_ip       = Host(ip="192.0.0.1")
        self.remotehost_hostname = Host(hostname="www.google.com")

    def test_unknown_hostname(self):
        self.assertRaises(ValueError, Host, hostname="unknownhostname")

    def test_wrong_args(self):
        #self.assertRaises(ValueError, Host, ip=None, hostname=None)
        with self.assertRaises(ValueError):
            Host(ip=None, hostname=None)

    def test_localhost(self):
        self.assertTrue(self.localhost_ip.is_localhost())
        self.assertTrue(self.localhost_hostname.is_localhost())

    def test_remote_hosts(self):
        self.assertFalse(self.remotehost_ip.is_localhost())
        self.assertFalse(self.remotehost_hostname.is_localhost())

    def test_localhost_equality(self):
        self.assertEqual(Host(ip="127.0.0.1"), Host(ip="127.53.1.245"))

    def test_get_real_ip(self):
        #self.assertFalse(
        #    Host(ip=self.localhost_ip.get_real_ip()).is_localhost())
        self.assertRaises(NotImplementedError, self.localhost_ip.get_real_ip)
        self.assertEqual(
            self.remotehost_ip.ip, self.remotehost_ip.get_real_ip())
开发者ID:whatevsz,项目名称:autobackup,代码行数:32,代码来源:test_host.py

示例3: test_glop

 def test_glop(self):
     h = Host()
     glop_contents = h.read(h.join(h.dirname(h.path_to_host_module()),
                                   'test_grammars', 'glop.g'))
     files = {'glop.g': glop_contents}
     output_files = files.copy()
     output_files['new_glop.g'] = glop_contents
     self.check_cmd(['-p', '-g', 'glop.g', '-o', 'new_glop.g'],
                    files=files, returncode=0, output_files=output_files)
开发者ID:moreati,项目名称:glop,代码行数:9,代码来源:main_test.py

示例4: exportgroup_create

    def exportgroup_create(self, name, project, tenant, varray, exportgrouptype, export_destination=None):
        '''
        This function will take export group name and project name  as input and
        It will create the Export group with given name.
        parameters:
           name : Name of the export group.
           project: Name of the project path.
           tenant: Container tenant name.
        return
            returns with status of creation. 
        '''
        # check for existance of export group.
        try:
            status = self.exportgroup_show(name, project, tenant)
        except SOSError as e:
            if(e.err_code == SOSError.NOT_FOUND_ERR):
                if(tenant == None):
                    tenant = ""
                    
                fullproj = tenant + "/" + project
                projuri = Project(self.__ipAddr, self.__port).project_query(fullproj) 
                nhuri = VirtualArray(self.__ipAddr, self.__port).varray_query(varray)
                
                parms = {
                'name' : name,
                'project' : projuri,
                'varray' : nhuri,
                'type' :exportgrouptype
                }
                if(exportgrouptype and export_destination):
                    if (exportgrouptype == 'Cluster'):
                        cluster_obj = Cluster(self.__ipAddr, self.__port)
                        try:
                            cluster_uri = cluster_obj.cluster_query(export_destination, fullproj)
                        except SOSError as e:
                            raise e
                        parms['clusters'] = [cluster_uri]
                    elif (exportgrouptype == 'Host'):
                        host_obj = Host(self.__ipAddr, self.__port)
                        try:
                            host_uri = host_obj.query_by_name(export_destination)
                        except SOSError as e:
                            raise e
                        parms['hosts'] = [host_uri]
                    # else:   # exportgrouptype == Exclusive
                        # TODO: add code for initiator                 
                body = json.dumps(parms)
                (s, h) = common.service_json_request(self.__ipAddr, self.__port, "POST", 
                                             self.URI_EXPORT_GROUP, body)

                o = common.json_decode(s)
                return o
            else:
                raise e
        if(status):
            raise SOSError(SOSError.ENTRY_ALREADY_EXISTS_ERR,
                           "Export group with name " + name + " already exists")
开发者ID:tylerbaker,项目名称:controller-openstack-cinder,代码行数:57,代码来源:exportgroup.py

示例5: exportgroup_remove_host

 def exportgroup_remove_host(self, exportgroupname, tenantname, projectname, hostlabels, sync):
     exportgroup_uri = self.exportgroup_query(exportgroupname, projectname, tenantname)
     host_uris = []
     hostObject = Host(self.__ipAddr, self.__port)
     for hostlabel in hostlabels:
         host_uris.append(hostObject.query_by_name(hostlabel, tenantname))
     parms = {}
     parms["host_changes"] = self._remove_list(host_uris)
     o = self.send_json_request(exportgroup_uri, parms)
     return self.check_for_sync(o, sync)
开发者ID:blueranger,项目名称:coprhd-controller,代码行数:10,代码来源:exportgroup.py

示例6: HostTest

class HostTest(unittest.TestCase):
    
    def setUp(self):
        self.host = Host('188.184.9.234:1000')
        self.host.addBlock('s1')
        self.host.addBlock('s1')
        self.host.addBlock('s2')
        self.host.addBlock('s2')
        self.host.addBlock('s3')

    def testHostname(self):
        self.assertEqual(self.host.hostname, 'webrlb01.cern.ch')
        
        host = Host('288.184.9.234:1000')
        self.assertEqual(host.hostname, '288.184.9.234')

    def test_addBlock(self):
        self.assertEqual(self.host.storages['s1'].blocks, 2)
        self.assertEqual(self.host.storages['s2'].blocks, 2)
        self.assertEqual(self.host.storages['s3'].blocks, 1)
        
    def test_blocksPerDiskAsString(self):
        self.assertEqual(self.host.blocksPerDiskAsString(), '1 2 2 ')
        
    def test_totalBlocks(self):
        self.assertEqual(self.host.totalBlocks(), 5)
        
    def test_avgBlocks(self):
        self.assertAlmostEqual(self.host.avgBlocks(), 1.66666, 4)
开发者ID:dlanza1,项目名称:hdfs-block-distribution,代码行数:29,代码来源:host_tests.py

示例7: exportgroup_create

    def exportgroup_create(self, name, project, tenant, varray, exportgrouptype, export_destination=None):
        """
        This function will take export group name and project name  as input
        and it will create the Export group with given name.
        parameters:
           name : Name of the export group.
           project: Name of the project path.
           tenant: Container tenant name.
        return
            returns with status of creation.
        """
        # check for existance of export group.
        try:
            status = self.exportgroup_show(name, project, tenant)
        except SOSError as e:
            if e.err_code == SOSError.NOT_FOUND_ERR:
                if tenant is None:
                    tenant = ""

                fullproj = tenant + "/" + project
                projObject = Project(self.__ipAddr, self.__port)
                projuri = projObject.project_query(fullproj)

                varrayObject = VirtualArray(self.__ipAddr, self.__port)
                nhuri = varrayObject.varray_query(varray)

                parms = {"name": name, "project": projuri, "varray": nhuri, "type": exportgrouptype}

                if exportgrouptype and export_destination:
                    if exportgrouptype == "Cluster":
                        cluster_obj = Cluster(self.__ipAddr, self.__port)
                        try:
                            cluster_uri = cluster_obj.cluster_query(export_destination, fullproj)
                        except SOSError as e:
                            raise e
                        parms["clusters"] = [cluster_uri]
                    elif exportgrouptype == "Host":
                        host_obj = Host(self.__ipAddr, self.__port)
                        try:
                            host_uri = host_obj.query_by_name(export_destination)
                        except SOSError as e:
                            raise e
                        parms["hosts"] = [host_uri]

                body = json.dumps(parms)
                (s, h) = common.service_json_request(self.__ipAddr, self.__port, "POST", self.URI_EXPORT_GROUP, body)

                o = common.json_decode(s)
                return o
            else:
                raise e

        if status:
            raise SOSError(SOSError.ENTRY_ALREADY_EXISTS_ERR, "Export group with name " + name + " already exists")
开发者ID:blueranger,项目名称:coprhd-controller,代码行数:54,代码来源:exportgroup.py

示例8: __init__

	def __init__(self):

		import random	
		from host import Host

		lett = ['s', 'w', 'a', 'e', 'l', 'v', 'm', 'i']
		namelis = [lett[random.randint(0, x)] for x in range(1,len(lett))]
		
		self._name = namelis[0].capitalize() + ''.join(namelis[1:])
		self._description = Host.getDescription()
		self._disappear = Host.getDisappearance()
		self._pointsGiven = random.randint(1, 10)
开发者ID:ssami,项目名称:python,代码行数:12,代码来源:angel.py

示例9: __init__

 def __init__(self, name, mymac=(0,0,0,0,0,0), myip=(0,0,0,0), destip=(0,0,0,0), pkts=1):
     Host.__init__(self, name, mymac, myip)
     self.pkts_to_send = pkts
     self.pkts_sent = 0
     self.received_pkt_count = 0
     self.current_destip_idx = 0
     if isinstance(destip, list):
         self.destip = map(lambda x: IpAddress(x), destip)
     else:
         self.destip = [IpAddress(destip)]
     self.flows_started = 0
     self.connections = {}
开发者ID:mcanini,项目名称:nice,代码行数:12,代码来源:tcp_client.py

示例10: add_host

 def add_host(self, name, port, healthcheck):
     h = Host(name,port)
     all_hosts = self.hosts
     if h in all_hosts:
         host = all_hosts[all_hosts.index(h)]
         if healthcheck not in host.healthchecks:
             host.add_healthcheck(healthcheck)
             host.reset()
         else:
             return True
     else:
         h.add_healthcheck(healthcheck)
         self.known_hosts[h] = datetime.datetime.now()
开发者ID:hobbeswalsh,项目名称:randomstuff,代码行数:13,代码来源:status.py

示例11: main

def main():
     # Set exit handler
    set_exit_handler(on_exit)

    # setup loggin
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s.%(msecs)d %(levelname)s %(module)s - %(funcName)s: %(message)s',
        datefmt="%Y-%m-%d %H:%M:%S"
    )


    # Create objects
    host = Host()
    host.start_server(80)
开发者ID:Hernrup,项目名称:fuisce,代码行数:15,代码来源:main.py

示例12: run

    def run(self):

        """
        Metodo run del thread, viene richiamato tramite start().
        Viene eseguito un loop che cerca a intervalli di 30 secondi
        nuovi hosts sulla rete e per ogni host che trova inizializza
        un thread che ne raccoglie le informazioni.
        I vari thread vengono raccolti all'interno di una lista.

        L'indirizzo della rete viene preso dalla linea di comando o se 
        non fornito si cerca di indovinarlo a partire dall'ip della 
        macchina (assumendo che la netmask sia 255.255.255.0 
        come spesso si verifica). 
        """

        self.known_hosts = []

        if '-n' in argv: 
            network_address = argv[argv.index('-n') + 1]

        elif '--network' in argv: 
            network_address = argv[argv.index('--network') + 1]

        else: 
            network_address = get_network_address()
        if not network_address:
            print("Cannot find network address... program will continue without network scanning!\n" +
                  "If this trouble persist, try providing the network address in the launch command!\n" +
                  "Press CTRL-C to terminate!")
            exit()

        while(True):

            hosts = host_discovery(network_address) 

            for host in hosts:
                if not (host in self.known_hosts):
                    self.known_hosts.append(host) 
                    print("Starting thread for host %s" % host) 
                    thread = Host(host)
                    self.threads.append(thread)
                    thread.start()

            for thread in self.threads:
                if not thread.is_alive:
                    self.known_hosts.remove(thread.info['ip'])

            sleep(30)
开发者ID:michelesr,项目名称:network-monitor-server,代码行数:48,代码来源:netmapping.py

示例13: initialize

	def initialize(self):
		if self.subnet:
			address_range = self.get_address_range(self.subnet)
			print('Size of network: ' + str(address_range.size()))
			self.alive_hosts = self.get_alive_hosts(address_range)

			for counter, ip in enumerate(self.alive_hosts):
				host = Host()
				host.ip = ip
				host.id += str(counter)
				self.host_list.append(host)

		else:
			host = Host()
			host.ip = self.address
			self.add_host(host)
开发者ID:logileifs,项目名称:NetCrawler,代码行数:16,代码来源:netcrawler.py

示例14: __init__

	def __init__(self, key, access, cluster):
		try:
			url = "http://169.254.169.254/latest/meta-data/"

			public_hostname = urlopen(url + "public-hostname").read()
			zone = urlopen(url + "placement/availability-zone").read()
			region = zone[:-1]
		except:
			sys.exit("We should be getting user-data here...")

		# the name (and identity) of the cluster (the master)
		self.cluster = cluster

		self.redis = redis.StrictRedis(host='localhost', port=6379)

		endpoint = "monitoring.{0}.amazonaws.com".format(region)
		region_info = RegionInfo(name=region, endpoint=endpoint)

		self.cloudwatch = CloudWatchConnection(key, access, region=region_info)
		self.namespace = '9apps/redis'

		self.events = Events(key, access, cluster)

		# get the host, but without the logging
		self.host = Host(cluster)
		self.node = self.host.get_node()
开发者ID:numan,项目名称:ReDiS,代码行数:26,代码来源:monitor.py

示例15: fileinfo

 def fileinfo(self, f):
     if f == "emplrec0451.log":
         output.openline()
         output.scr.addstr("looks like ol' 0451 here was supposed to be at SenseNet earlier.")
         if self.state == 2:
             self.state = 3
     return Host.fileinfo(self,f)
开发者ID:Kha,项目名称:HottestCatOnTheBlock,代码行数:7,代码来源:cats.py


注:本文中的host.Host类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。