[Tutor] Doubt in RPC XML lib

Varun Soundararajan s.varun at gmail.com
Thu Sep 9 20:37:42 CEST 2004


I hv attached the two files. Actually what i am trying to do is that,
i replicate the gethosts.py and servers.py code in every system. in
every system when i start my python code, i check all servers of the
same type and add to my active hosts list. ( i do taht in gethosts.py)
in the servers.py, i serve my own server at 10001 and rpc server at
8000 using thread. My server at 10001 authenticates with other server
of my type by sending some hashed data and getting it back (just to
ensure that i am not adding some other server listening at 10001).
Now my qn is,
if i want to access a code i call:
server.somefunction()
now since i have the list of functions of form (['1.fn1',
'1.fn2','2.fn1' etc] ) when i want to call the fn1 of server 0 i shd
call
hosts_server_access[0].fn1() . but i want the user to choose that. Now
how do i do that.
in other words.
if i wanna call fn1 of server 0 i shd be able to call(say)
hosts_server_access[0][1]() or something like that.
pls help
thanks in advance
-Varun
-------------- next part --------------
import ConfigParser
import xmlrpclib
import md5
import socket


class Hosts:
    """ Hosts: On instantiating, the object reads from file hosts.ini and
    finds all live hosts"""
    
    hostlist=[]
    alivehosts=[]
    PORT=10001
    hosts_functions=[]
    hosts_server_access=[]

    
    def __init__(self):
        self.hostlist=self.gethosts("hosts.ini")
        for host in self.hostlist:
            if self.isAlive(host,self.PORT):
                self.alivehosts.append(host)

    def __str__(self):
        return str(self.alivehosts)

    
    def gethosts(self,filename):
        """ Gets a list of hostnames from the file <i>fFilename</i>.
        returns a list of hosts declared in the filename """
        
        f=open(filename)
        configobj=ConfigParser.ConfigParser()
        configobj.readfp(f)
        hosts=[]
        values=configobj.items("hosts")
        for i in configobj.options("hosts"):
            hosts.append(configobj.get("hosts",i))
        return hosts


    def isAlive(self,HOST,PORT):
        """ Checks if the particular host <i> hostname</i>is alive and running
        at port <i>port</i>
        Todo: send some arbitrary encrypted string accepted only
        if that server is of my type """
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(0.5)
        try:
            s.connect((HOST, PORT))
            m=md5.new()
            m.update(socket.gethostbyname(socket.gethostname()))
            s.send(m.hexdigest())
            recvdata=s.recv(1024)
            #i send and receive the same data
            #just to ensure that i am recognizing
            #a server of my type. Cant help if
            #some custom server listens to same port
            #and sends back the received data
            #without changing the data
            
            if recvdata == m.hexdigest():
                return True
            else:
                return False
            
        except socket.error, msg:
            s.close()
            return False
        
    def updateFunctionList(self):
        """ Updates hosts_functions list with the list of
        functions avaliable in live servers """
        self.hosts_functions=[]
        for host in range(0,len(self.alivehosts)):
            hostname="http://"+self.alivehosts[host]+":8000"
            #print "hostname=",hostname
            server=xmlrpclib.ServerProxy(uri=hostname)
            self.hosts_server_access.append(server)
            #print server.system.listMethods()
            fnlist=[]
            fnlist=server.system.listMethods()
            for fn in fnlist:
                apdata="%d.%s" %(host,fn)
                self.hosts_functions.append(apdata)
        return self.hosts_functions
    def access_list(self):
        return self.hosts_server_access
        
if __name__=="__main__":
    hosts=Hosts()
    print hosts.updateFunctionList()
-------------- next part --------------
import socket
import threading
from SimpleXMLRPCServer import *
import md5

def myserver():
        HOST = 'localhost'                 # Symbolic name meaning the local host
	PORT = 10001              # Arbitrary non-privileged port
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.bind((HOST, PORT))
	while 1:
                s.listen(1)
                conn, addr = s.accept()
                print 'Connected by', addr
                data = conn.recv(1024)
                if not data: pass
		conn.send(data)
                conn.close()
                print "Connection closed"

def MyRPCServer():
	server = SimpleXMLRPCServer(("localhost", 8000))
	server.register_function(pow)
	server.register_function(lambda x,y: x+y, 'add')
	server.register_introspection_functions()
#       server.register_instance(MyFuncs())
        print server.system_listMethods()
	server.serve_forever()

if __name__=="__main__":
	mys=threading.Thread(target=myserver)
	rpcs=threading.Thread(target=MyRPCServer)
        mys.start()
        rpcs.start()


More information about the Tutor mailing list