Statistics
| Branch: | Revision:

iof-tools / BGPpysim / bgpSimlulator.py @ de0e8e06

History | View | Annotate | Download (5.16 KB)

1
from argparse import ArgumentParser
2
import networkx as nx
3
from pprint import pprint
4
from util.EventScheduler import EventScheduler
5
from util.node import Node
6
from time import sleep
7
from tqdm import tqdm
8
import random
9
import sys
10
import datetime
11
import os
12
import shutil
13
from util.routing_table import Route
14
import code  # code.interact(local=dict(globals(), **locals()))
15

    
16
MAX_DURATION = 100
17

    
18

    
19
class bgpSim(object):
20

    
21
    def __init__(self, graph, sim_dir):
22
        self.G = graph
23
        self.sim_dir = sim_dir
24
        self.initNodes(G)
25

    
26
    def initNodes(self, G):
27
        print("InitNodes")
28
        nodes = {}
29
        # Node attributes
30
        for n in self.G.nodes(data=True):
31
            node_id = n[0]
32
            node_type, prefixes = 'C', []
33
            if 'type' in n[1]:
34
                node_type = n[1]['type']
35
            if 'destinations' in n[1]:
36
                prefixes = n[1]['destinations'].split(',')
37
            nodes[node_id] = Node(node_id, self.sim_dir, node_type, prefixes)
38

    
39
        # Edge attributes
40
        for e in self.G.edges(data=True):
41
            #source, target = e[0], e[1]
42
            edge_type, end1, end2, mrai1, mrai2, customer = e[2]['type'], e[2]['termination1'], e[
43
                2]['termination2'], float(e[2]['mrai1']), float(e[2]['mrai2']), e[2]['customer']
44
            if edge_type == 'peer':
45
                nodes[end1].neighs[end2] = {
46
                    'relation': 'peer', 'mrai': mrai1, 'pynode': nodes[end2]}
47
                nodes[end2].neighs[end1] = {
48
                    'relation': 'peer', 'mrai': mrai2, 'pynode': nodes[end1]}
49
            elif edge_type == 'transit':
50
                c, p = (end1, end2) if customer == end1 else (end2, end1)
51
                p2c, c2p = (mrai1, mrai2) if customer == end1 else (
52
                    mrai2, mrai1)
53
                # my neigh is my provider
54
                nodes[c].neighs[p] = {
55
                    'relation': 'provider', 'mrai': c2p, 'pynode': nodes[p]}
56
                # my neigh is my customer
57
                nodes[p].neighs[c] = {
58
                    'relation': 'customer', 'mrai': p2c, 'pynode': nodes[c]}
59
        self.nodes = nodes
60

    
61
    def jitter(self):
62
        return [-1, 1][random.randrange(2)]*random.uniform(0, 0.866)
63

    
64
    def scedule_initial_events(self, sched):
65
        for nodeID in self.nodes:
66
            sched.schedule_event(
67
                1.0 + self.jitter(), {'actor': nodeID, 'action': 'CHECK_RX'})
68
            '''if self.nodes[nodeID].exportPrefixes:
69
                # Primo annuncio a tutti i vicini
70
                for prefix in self.nodes[nodeID].exportPrefixes:
71
                    for neigh in self.nodes[nodeID].neighs:
72
                        route = Route(prefix, {'AS_PATH': nodeID})
73
                        sched.schedule_event(
74
                            0.0 + self.jitter(), {'actor': nodeID,
75
                                           'action': 'MRAI_DEADLINE', 'route': route, 'neigh': neigh})'''
76

    
77
    def runSimulation(self):
78
        sched = EventScheduler()
79
        self.scedule_initial_events(sched)
80
        print("Simulation started")
81
        time = 0
82
        with tqdm(total=MAX_DURATION) as pbar:
83
            while(sched.elapsed_time() < MAX_DURATION and len(sched.queue) > 0):
84
                event = sched.pop_event()
85
                current_time = sched.elapsed_time()
86
                node = self.nodes[event['actor']]
87
                # code.interact(local=dict(globals(), **locals()))
88
                if event['action'] == 'CHECK_RX':
89
                    node.processRXupdates(sched.elapsed_time())
90
                    # reschedule same event of type 'CHECK_RX'
91
                    sched.schedule_event(current_time + self.jitter(), event)
92
                elif event['action'] == 'MRAI_DEADLINE':
93
                    node.sendUpdate(
94
                        event['route'], event['neigh'], sched.elapsed_time())
95
                sleep(0.1)
96
                time += 10
97
                pbar.update(1)
98

    
99

    
100
def config_out_path(outPath):
101
    if not os.path.exists(outPath):
102
        raise Exception("\u001b[31mCannot find the outpath you provided!\n")
103
    else:
104
        start = datetime.datetime.now().strftime("%Hh%Mm%Ss_%d-%m-%Y")
105
        cdir = outPath + '/' + 'bgpSim_' + start
106
        if os.path.exists(cdir):
107
            shutil.rmtree(cdir)
108
        os.makedirs(cdir)
109
        return cdir
110

    
111

    
112
if __name__ == '__main__':
113
    # Define and get required args
114
    parser = ArgumentParser()
115
    parser.add_argument("-g", "--graph",
116
                        dest="graph", required=True, action="store",
117
                        help="Graph topology describer, .graphml format.")
118
    parser.add_argument("-w", "--write-to", dest="writeto",
119
                        default="out/", action="store",
120
                        help="Output folder for simulation")
121
    args = parser.parse_args()
122
    graph_path = args.graph
123
    output_folder = args.writeto
124
    sim_dir = config_out_path(output_folder)
125

    
126
    G = nx.read_graphml(path=graph_path)
127

    
128
    # Initialize simulator and start simulation
129
    sim = bgpSim(G, sim_dir)
130
    sim.runSimulation()
131
    print("FINISHED SIMULATION, MAX TIME OR CONVERGENCE REACHED")
132
    for n in sim.nodes.values():
133
        print("RT of NODE: "+n.ID)
134
        n.RT.dumps()
135
    code.interact(local=dict(globals(), **locals()))