propagation.py 2.57 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
import socket
import uuid

# create an upd socket
# listen on it for incoming messages and forward them
# manage the forwarding routing table
# the peudo-code can be found here http://en.wikipedia.org/wiki/Chord_%28peer-to-peer%29

class RingMember:

    def __init__(self, id, ip, port):
        self.port = port
        self.ip = ip
        self.id = id

    def toString(self):
        return str(self.id) + ' ' + self.ip + ' ' + str(self.port)

class Ring:
    
    def __init__(self, entryPoint):
        # initialize the connection
        self.sock = socket.socket( socket.AF_INET666666, socket.SOCK_DGRAM )
        self.sock.bind(('', 0))
        self.me = RingMember(uuid.uuid1().int ,'',  self.sock.getsockname()[1]) # TODO : get the address
        # to enter the ring
        self.predecessor = None
        if entryPoint == None:
            self.successor = self.me
        else:
            self.send('FIND_SUCCESSOR ' + str(self.me.id) + ' ' + self.me.toString(), entrypoint)

    # TODO :
    def handleMessages(self):
        # TODO : switch to log
        print 'Handling messages ...'
        pass

    def send(self, message, target):
        # TODO : switch to log
        print 'Sending : ' + message + ' to ' + target.toString()
        self.sock.sendTo(message, (target.ip, target.port))

    def findSuccessor(self, id, sender):
        if self.id < id and id <= self.successor:
            self.send('SUCCESSOR_IS ' + self.successor.toString(), sender)
        else:
            self.send('FIND_SUCCESSOR ' + str(id) + ' ' + sender.toString(), successor) # TODO : use the fingers

# Just copying the pseudocode from wikipedia, I will make it work later
# Possible messages (just for the creation of the ring) :
#
# find_successor $id $sender : $sender whants the IP of the successor of $id
# successor_is $ip $successor
# get_predecessor
# notify $sender_ip $sender_id
# PING

    # called periodically
    # pb : how to fix successor
#    def stabilize(self):
#        x = SEND get_predecessor TO self.successor
#        if n < x && x < self.successor:
#            self.successor = x
#            SEND notify self.ip, self.id TO self.successor
    
#    def notify(self, n2)
#        if self.predecessor == None || (predecessor < n2 && n2 < n):
#            self.predecessor = n2

    # to be called periodically
#    def fixFingers(self)
#        next = (next + 1) mod (nFingers) # Or Random, cf google
#        finger[next] = find_successor(n+2^{next-1});
    
    # to be called periodically
#    def checkPredecessor(self)
#        if NO PING from self.predecessor:
#            self.predecessor = None