示例#1
0
def remove_vertical_bridge(g: dijkstar.Graph, position):
    x, y = position
    g.remove_edge((x, y + 1), (x, y - 1))
    g.remove_edge((x, y - 1), (x, y) + 1)
示例#2
0
class LSrouter(Router):
    """Link state routing protocol implementation."""
    def __init__(self, addr, heartbeatTime):
        """TODO: add your own class fields and initialization code here"""
        Router.__init__(self, addr)  # initialize superclass - don't remove
        self.heartbeatTime = heartbeatTime
        self.last_time = 0
        # Hints: initialize local state
        self.link_state = {}  #APNA LINK STATE
        self.link_state_local = {}  #BAKI SUB KA LINK STATE
        self.sequence_number = 0  #SEND KARTAY WAKT SEQ NUM
        self.check_sequence_number = {}  #RECIEVE KARTAY WAKT SEQ NUM
        self.network_graph = Graph(undirected=True)  #GRAPH
        self.forwarding_table = {}  #FRWD TABLE

    def handlePacket(self, port, packet):
        """TODO: process incoming packet"""
        if packet.isTraceroute():
            # Hints: this is a normal data packet
            # if the forwarding table contains packet.dstAddr
            #   send packet based on forwarding table, e.g., self.send(port, packet)
            self.sendNormalPacket(packet)
        else:
            # Hints: this is a routing packet generated by your routing protocol
            # check the sequence number
            # if the sequence number is higher and the received link state is different
            #   update the local copy of the link state
            #   update the forwarding table
            #   broadcast the packet to other neighbors
            recieved_link_state, received_sequence_number = loads(
                packet.content)
            if packet.srcAddr not in self.check_sequence_number.keys():
                self.check_sequence_number[packet.srcAddr] = 0
            if self.check_sequence_number[packet.srcAddr] < int(
                    received_sequence_number):
                if recieved_link_state not in self.link_state_local.values():
                    self.check_sequence_number[packet.srcAddr] = int(
                        received_sequence_number)
                    self.updateNetworkGraph(packet, recieved_link_state)
                    self.updateForwardingTable()
                    self.forwardLinkState(packet, port)

    def updateNetworkGraph(self, packet, recieved_link_state):
        if packet.srcAddr in self.link_state_local.keys():
            for link in self.link_state_local[packet.srcAddr].values():
                if link[1] in self.network_graph[link[0]].keys():
                    self.network_graph.remove_edge(link[0], link[1])
        self.link_state_local[packet.srcAddr] = recieved_link_state
        for link in recieved_link_state.values():
            self.network_graph.add_edge(link[0], link[1], int(link[2]))

    def updateForwardingTable(self):
        self.forwarding_table.clear()
        for port_no, link in self.link_state.items():
            self.forwarding_table[link[1]] = (link[1], port_no)
        for link_state in self.link_state_local.values():
            for link in link_state.values():
                try:
                    path = find_path(self.network_graph, self.addr, link[1])
                    port = self.forwarding_table[path.nodes[1]][1]
                    self.forwarding_table[link[1]] = (path.nodes[1], port)
                except:
                    pass

    def forwardLinkState(self, packet, port):
        for port_no in self.link_state.keys():
            if port_no != port:
                self.send(port_no, packet)

    def sendNormalPacket(self, packet):
        if packet.dstAddr in self.forwarding_table.keys():
            port = self.forwarding_table[packet.dstAddr][1]
            self.send(port, packet)

    def forwardLinkState(self, packet, port):
        for port_no in self.link_state.keys():
            if port_no != port:
                self.send(port_no, packet)

    def handleNewLink(self, port, endpoint, cost):
        """TODO: handle new link"""
        # Hints:
        # update the forwarding table
        # broadcast the new link state of this router to all neighbors
        self.link_state[port] = (self.addr, endpoint, cost)
        self.network_graph.add_edge(self.addr, endpoint, cost)
        self.forwarding_table[endpoint] = (endpoint, port)
        self.sendLinkState()

    def sendLinkState(self):
        message_content = dumps([self.link_state, self.sequence_number])
        for port_no, link in self.link_state.items():
            send_packet = Packet(Packet.ROUTING,
                                 self.addr,
                                 link[1],
                                 content=message_content)
            self.send(port_no, send_packet)
        self.sequence_number += 1

    def handleRemoveLink(self, port):
        """TODO: handle removed link"""
        # Hints:
        # update the forwarding table
        # broadcast the new link state of this router to all neighbors
        link = self.link_state[port]
        del self.link_state[port]
        if link[1] in self.link_state_local.keys():
            del self.link_state_local[link[1]]
        self.network_graph.remove_edge(self.addr, link[1])
        self.updateForwardingTable()
        self.sendLinkState()

    def handleTime(self, timeMillisecs):
        """TODO: handle current time"""
        if timeMillisecs - self.last_time >= self.heartbeatTime:
            self.last_time = timeMillisecs
            # Hints:
            # broadcast the link state of this router to all neighbors
            self.sendLinkState()

    def debugString(self):
        """TODO: generate a string for debugging in network visualizer"""
        return ""
示例#3
0
def remove_horizontal_bridge(g: dijkstar.Graph, position):
    print("removing horizontal for {}".format(position))
    x, y = position
    g.remove_edge((x - 1, y), (x + 1, y))
    g.remove_edge((x + 1, y), (x - 1, y))
示例#4
0
class LSrouter(Router):
    """Link state routing protocol implementation."""
    def __init__(self, addr, heartbeatTime):
        """TODO: add your own class fields and initialization code here"""
        Router.__init__(self, addr)  # initialize superclass - don't remove
        self.heartbeatTime = heartbeatTime
        self.last_time = 0
        self.forwarding_table = {}
        self.routing_table = {}
        self.graph = Graph()
        self.seqno = "1"
        self.check = True
        # Hints: initialize local state
        pass

    def handlePacket(self, port, packet):
        """TODO: process incoming packet"""
        if packet.isTraceroute():
            # Hints: this is a normal data packet
            # if the forwarding table contains packet.dstAddr
            #   send packet based on forwarding table, e.g., self.send(port, packet)
            for x, y in self.forwarding_table.items():
                if packet.dstAddr == x:
                    first = int(y.split(" ")[0], 10)
                    self.send(first, packet)

            try:
                var = find_path(self.graph, self.addr, packet.dstAddr)
                if var.total_cost > 1:
                    for x, y in self.forwarding_table.items():
                        temp = var.nodes[1]
                        if x == temp:
                            first = int(y.split(" ")[0], 10)
                            self.send(first, packet)
            except:
                pass

        else:

            #   Hints: this is a routing packet generated by your routing protocol
            #   check the sequence number
            #   if the sequence number is higher and the received link state is different
            #   update the local copy of the link state
            #   update the forwarding table
            #   broadcast the packet to other neighbors

            rec = packet.content.split(" ", 1)
            temp = rec[0]
            seqno_received = int(temp, 10)

            received_routing_table = loads(packet.content.split(" ", 1)[1])

            if self.addr == packet.srcAddr:
                return

            for x, y in self.routing_table.items():
                if x == packet.srcAddr:
                    if y >= seqno_received:
                        return

            for x, y in self.forwarding_table.items():
                if ord(x) <= 90:
                    temp = y.split(" ")[0]
                    t = int(temp, 10)
                    if not port == t:
                        self.send(t, packet)

            try:
                for x in self.graph[packet.srcAddr]:
                    if self.graph[packet.srcAddr][x] == packet.srcAddr:
                        continue
                    Check = False
                    for y in received_routing_table.keys():
                        if x == y:
                            Check = True
                            break

                    if Check == False:
                        self.graph.remove_edge(packet.srcAddr, x)
            except:
                pass

            for x in received_routing_table.keys():
                self.graph.add_edge(
                    packet.srcAddr, x,
                    int(received_routing_table[x].split(" ")[1], 10))

            self.routing_table[packet.srcAddr] = seqno_received

    def handleNewLink(self, port, endpoint, cost):
        """TODO: handle new link"""
        # Hints:
        # update the forwarding table
        # broadcast the new link state of this router to all neighbors
        self.graph.add_edge(self.addr, endpoint, cost)
        self.forwarding_table[endpoint] = str(port) + " " + str(cost)

        for x, y in self.forwarding_table.items():
            if ord(x) < 90:
                temp = self.forwarding_table[endpoint].split(" ")[0]
                t = int(temp, 10)
                port = t
                jsn_str = dumps(self.forwarding_table)
                t_str = self.seqno + " " + jsn_str
                pac = Packet(Packet.ROUTING, self.addr, port, t_str)
                self.send(port, pac)
                t_int = int(self.seqno, 10)
                self.seqno = str(t_int + 1)

    def handleRemoveLink(self, port):
        """TODO: handle removed link"""
        # Hints:
        # update the forwarding table
        # broadcast the new link state of this router to all neighbors
        for x, y in self.forwarding_table.items():
            temp = y.split(" ")[0]
            to_rmv = int(temp, 10)
            if port == to_rmv:
                break
        self.forwarding_table.pop(x, None)
        self.graph.remove_edge(self.addr, x)

        for x, y in self.forwarding_table.items():
            if ord(x) < 90:
                pac = y.split(" ")[0]
                port = int(pac, 10)
                jsn = dumps(self.forwarding_table)
                t_str = self.seqno + " " + jsn
                pkg = Packet(Packet.ROUTING, self.addr, port, t_str)
                self.send(port, pkg)
                t_int = int(self.seqno, 10)
                self.seqno = str(t_int + 1)

    def handleTime(self, timeMillisecs):
        """TODO: handle current time"""
        if timeMillisecs - self.last_time >= self.heartbeatTime:
            self.last_time = timeMillisecs
            # Hints:
            # broadcast the link state of this router to all neighbors
            for x, y in self.forwarding_table.items():
                if ord(x) < 90:
                    temp = y.split(" ")[0]
                    port = int(temp, 10)
                    jsn = dumps(self.forwarding_table)
                    t_str = self.seqno + " " + jsn
                    pac = Packet(Packet.ROUTING, self.addr, port, t_str)
                    self.send(port, pac)

    def debugString(self):
        """TODO: generate a string for debugging in network visualizer"""
        print("Address: ", self.addr)
        print("Routing Table: ", self.routing_table)
        print("Forwarding Table: ", self.forwarding_table)
        print("Graph : ", self.graph)
        print()
        try:
            print(find_path(self.graph, "a", "b"))
        except:
            pass
        return ""
示例#5
0
from dijkstar import Graph, find_path
print("hello world")



graph = Graph()

filepath = "moreno_beach.txt"
with open(filepath) as fp:
    for line in fp:
        node1, node2, edge = line.split()
        graph.add_edge(int(node1), int(node2), int(edge))

print(graph.node_count)
print(graph.edge_count)
a = find_path(graph, 1, 2)
graph.remove_edge(1, 2)
b = find_path(graph, 1 , 3)
print(b)
print(graph.node_count)
print(graph.edge_count)
print(a)


示例#6
0
class LSrouter(Router):
    """Link state routing protocol implementation."""

    def __init__(self, addr, heartbeatTime):
        """TODO: add your own class fields and initialization code here"""
        Router.__init__(self, addr)  # initialize superclass - don't remove
        self.heartbeatTime = heartbeatTime
        self.last_time=0
        self.addr=addr
        self.sequence=0
        self.state=[]
        self.forward_table={}
        self.graph=Graph(undirected=True)
        self.add_status=True
        self.last_seq={}
        # Hints: initialize local state

    def handlePacket(self, port, packet):
        """TODO: process incoming packet"""
        if packet.srcAddr != self.addr:
            if packet.isTraceroute():
                # Hints: this is a normal data packet
                # if the forwarding table contains packet.dstAddr
                #   send packet based on forwarding table, e.g., self.send(port, packet)
                try:
                    path=find_path(self.graph,self.addr,packet.dstAddr)
                    node=path.nodes[1]
                    if node in self.forward_table.keys():
                        self.send(self.forward_table[node],packet)
                except Exception as e:
                    pass

            else:
                # Hints: this is a routing packet generated by your routing protocol
                # check the sequence number
                #   if the sequence number is higher and the received link state is different
                #   update the local copy of the link state
                #   update the forwarding table
                #   broadcast the packet to other neighbors
                msg=loads(packet.getContent())
                for i in self.forward_table.keys():
                    if self.forward_table[i] == port:
                        src=i
                        break

                if msg['removal']==True and self.last_seq[packet.srcAddr] < msg['seq']:
                    
                    #update seq
                    self.last_seq[packet.srcAddr]=msg['seq']

                    #update graph
                    try:
                        self.graph.remove_edge(msg['state'][0],msg['state'][1])
                    except Exception as E:
                        print(E)

                    #broadcast
                    self.sequence+=1
                    for i in self.forward_table.keys():
                        if self.forward_table[i] == port:
                            continue
                        else:
                            self.send(self.forward_table[i],packet) 



                elif packet.srcAddr not in self.last_seq.keys() or self.last_seq[packet.srcAddr] < msg['seq']:
                   
                    #update seq
                    self.last_seq[packet.srcAddr]=msg['seq'] 
                    
                    #update graph
                    for i in msg['state']:
                        a=i[0]
                        b=i[1]
                        c=i[2]
                        self.graph.add_edge(a,b,c)
                    
                    #update forwarding table
                    if src not in self.forward_table:
                        self.forward_table[src]=port

                    #broadcasting
                    self.sequence+=1
                    for i in self.forward_table.keys():
                        if self.forward_table[i]==port:
                            continue
                        else:
                            self.send(self.forward_table[i],packet)

                #print('here {} {}'.format(self.sequence,msg['seq']))
        

    def handleNewLink(self, port, endpoint, cost):
        """TODO: handle new link"""
        # Hints:
        # update the forwarding table
        # broadcast the new link state of this router to all neighbors

        #updataing forward table
        self.forward_table[endpoint]=port

        #make state
        state=[self.addr,endpoint,cost]
        
        #update state
        if state not in self.state:
            self.state.append(state)

        #update graph
        self.graph.add_edge(self.addr,endpoint,cost)

        #broadcast
        self.sequence+=1
        for i in self.forward_table.keys():
            a=Packet(2,self.addr,i,content=dumps({'state':self.state,'seq':self.sequence,'removal':False}))
            self.send(self.forward_table[i],a)


        


    def handleRemoveLink(self, port):
        """TODO: handle removed link"""
        # Hints:
        # update the forwarding table
        # broadcast the new link state of this router to all neighbors 

        #get addr
        for i in self.forward_table.keys():
            if self.forward_table[i]==port:
                a=i
                break

        #update forward table
        del self.forward_table[a]
        
        #remove edge
        self.graph.remove_edge(self.addr,a)

        #update state
        for i in self.state:
            if i[1] == a:
                self.state.remove(i)

        #just to be consistent
        state=[self.addr,a,69]

        #broadcasting
        self.sequence+=1
        for i in self.forward_table.keys():
            if i == a:
                continue
            else:
                b=Packet(2,self.addr,i,content=dumps({'state':state,'seq':self.sequence,'removal':True}))
                self.send(self.forward_table[i],b)
        


    def handleTime(self, timeMillisecs):
        """TODO: handle current time"""
        if timeMillisecs - self.last_time >= self.heartbeatTime:
            self.last_time = timeMillisecs
            # Hints:
            # broadcast the link state of this router to all neighbors
            self.sequence+=1
            for i in self.forward_table.keys():
                a=Packet(2,self.addr,i,content=dumps({'state':self.state,'seq':self.sequence,'removal':False}))
                self.send(self.forward_table[i],a)

    def debugString(self):
        """TODO: generate a string for debugging in network visualizer"""
        return dumps(str(self.graph))
class LSrouter(Router):
    """Link state routing protocol implementation."""
    def __init__(self, addr, heartbeatTime):
        """TODO: add your own class fields and initialization code here"""
        Router.__init__(self, addr)  # initialize superclass - don't remove
        self.heartbeatTime = heartbeatTime
        self.last_time = 0
        self.G = Graph(undirected=True)
        self.SeqNum = {}
        self.Neighbours = {
        }  #Dictionary with key as address and cost and seqnum as values
        self.Curr_Seq = 0
        # Hints: initialize local state

    def handlePacket(self, port, packet):
        """TODO: process incoming packet"""

        if packet.isTraceroute():
            # Hints: this is a normal data packet
            # if the forwarding table contains packet.dstAddr
            #   send packet based on forwarding table, e.g., self.send(port, packet)

            try:
                Shortest = find_path(self.G, self.addr, packet.dstAddr)
                self.send(self.Neighbours[Shortest.nodes[1]]['Port'], packet)
            except:
                return

        else:
            # Hints: this is a routing packet generated by your routing protocol
            # check the sequence number
            # if the sequence number is higher and the received link state is different
            #   update the local copy of the link state
            #   update the forwarding table
            #   broadcast the packet to other neighbors

            Cont = loads(packet.content)

            #Cont[0] is the sender
            #Cont[1] is sender neighbours
            #Cont[2] is seqnum

            if Cont[0] in self.SeqNum.keys():  # Node in SeqNum dictionary
                if Cont[2] <= self.SeqNum[
                        Cont[0]]:  # Discard packet as it is old
                    return

            self.SeqNum[Cont[0]] = Cont[2]

            if Cont[0] in self.G.keys():

                if len(Cont[1]) < len(self.G[Cont[0]]):
                    for node in self.G[Cont[0]]:
                        if node not in Cont[1]:  # Link Removed
                            self.G.remove_edge(Cont[0], node)
                            break

                else:  #Link added or updated
                    for key, _ in Cont[1].items():
                        self.G.add_edge(Cont[0], key, Cont[1][key]['Cost'])

                for key, _ in self.Neighbours.items():  #Packet Flooding
                    if (key == Cont[0]):
                        continue

                    self.send(self.Neighbours[key]['Port'], packet)

    def handleNewLink(self, port, endpoint, cost):
        """TODO: handle new link"""
        # Hints:
        # update the forwarding table
        # broadcast the new link state of this router to all neighbors
        # print("\nSelf.Addr: ",self.addr,"Endpoint: ",endpoint, "Cost: ",cost, "Port: ",port)
        self.G.add_edge(self.addr, endpoint, cost)

        self.Neighbours[endpoint] = {}
        self.Neighbours[endpoint]['Cost'] = cost
        self.Neighbours[endpoint]['Port'] = port

        self.Curr_Seq = self.Curr_Seq + 1
        Content = dumps([self.addr, self.Neighbours, self.Curr_Seq])

        for key, _ in self.Neighbours.items():
            Pack = Packet(Packet.ROUTING, self.addr, self.Neighbours[key],
                          Content)
            self.send(self.Neighbours[key]['Port'], Pack)

    def handleRemoveLink(self, port):
        """TODO: handle removed link"""
        # Hints:
        # update the forwarding table
        # broadcast the new link state of this router to all neighbors

        for key, _ in self.Neighbours.items():
            if self.Neighbours[key]['Port'] == port:
                Link = key
                break

        del self.Neighbours[Link]
        self.G.remove_edge(self.addr, Link)

        self.Curr_Seq = self.Curr_Seq + 1
        Content = dumps([self.addr, self.Neighbours, self.Curr_Seq])

        for k, _ in self.Neighbours.items():
            Pack = Packet(Packet.ROUTING, self.addr, self.Neighbours[k],
                          Content)
            self.send(self.Neighbours[k]['Port'], Pack)

    def handleTime(self, timeMillisecs):
        """TODO: handle current time"""
        if timeMillisecs - self.last_time >= self.heartbeatTime:
            # Hints:
            # broadcast the link state of this router to all neighbors
            self.Curr_Seq = self.Curr_Seq + 1
            Content = dumps([self.addr, self.Neighbours, self.Curr_Seq])

            for k, _ in self.Neighbours.items():
                Pack = Packet(Packet.ROUTING, self.addr, self.Neighbours[k],
                              Content)
                self.send(self.Neighbours[k]['Port'], Pack)

            self.last_time = timeMillisecs

    def debugString(self):
        """TODO: generate a string for debugging in network visualizer"""
        return ""