Пример #1
0
    def run(self, node, bidir, output_file):

        try:
            import matplotlib.pyplot as plt
            import networkx as nx
        except Exception:
            print("matplotlib and networkx needed for drawing. Skipping")
            sys.exit(1)

        publication = self.client.dump_all_with_prefix(Consts.ADJ_DB_MARKER)
        nodes = self.get_node_to_ips().keys() if not node else [node]
        adjs_map = utils.adj_dbs_to_dict(publication, nodes, bidir,
                                         self.iter_publication)
        G = nx.Graph()
        for this_node_name, db in adjs_map.items():
            for adj in db['adjacencies']:
                G.add_edge(this_node_name, adj['otherNodeName'], **adj)

        # hack to get nice fabric
        # XXX: FB Specific
        pos = {}
        eswx = 0
        sswx = 0
        fswx = 0
        rswx = 0
        for node in G.nodes():
            if 'esw' in node:
                pos[node] = [eswx, 3]
                eswx += 10
            elif 'ssw' in node:
                pos[node] = [sswx, 2]
                sswx += 10
            elif 'fsw' in node:
                pos[node] = [fswx, 1]
                fswx += 10
            elif 'rsw' in node:
                pos[node] = [rswx, 0]
                rswx += 10

        maxswx = max(eswx, sswx, fswx, rswx)
        if maxswx > 0:
            # aesthetically pleasing multiplier (empirically determined)
            plt.figure(figsize=(maxswx * 0.3, 8))
        else:
            plt.figure(figsize=(len(G.nodes()) * 2, len(G.nodes()) * 2))
            pos = nx.spring_layout(G)
        plt.axis('off')
        nx.draw_networkx(G, pos, ax=None, alpha=0.5, font_size=8)
        if node:
            edge_labels = dict([
                ((u, v), str(d['ifName']) + ' metric: ' + str(d['metric']))
                for u, v, d in G.edges(data=True)
            ])
            nx.draw_networkx_edge_labels(G,
                                         pos,
                                         edge_labels=edge_labels,
                                         font_size=6)

        print('Saving topology to file => {}'.format(output_file))
        plt.savefig(output_file)
Пример #2
0
 def run(self, nodes, bidir, json):
     adj_dbs = self.client.get_adj_dbs()
     adjs_map = utils.adj_dbs_to_dict(adj_dbs, nodes, bidir, self.iter_dbs)
     if json:
         utils.print_adjs_json(adjs_map)
     else:
         utils.print_adjs_table(adjs_map, self.enable_color)
Пример #3
0
    def print_adj(self, publications: Dict[str, openr_types.Publication],
                  nodes, bidir, json):
        adjs_list = defaultdict(list)
        # get list of adjancencies from each area and add it to the final
        # adjacency DB.
        adjs_map = {}
        for area, publication in publications.items():
            adjs = utils.adj_dbs_to_dict(publication, nodes, bidir,
                                         self.iter_publication)
            # handle case when area has no adjacencies
            if len(adjs):
                adjs_map = adjs
            else:
                continue
            for key, val in adjs_map.items():
                for adj_entry in val["adjacencies"]:
                    adj_entry["area"] = area
                adjs_list[key].extend(val["adjacencies"])

        for key, val in adjs_list.items():
            adjs_map[key]["adjacencies"] = val

        if json:
            utils.print_json(adjs_map)
        else:
            utils.print_adjs_table(adjs_map)
Пример #4
0
 def _run(self, client: OpenrCtrl.Client, nodes: set, node: Any,
          interface: Any) -> None:
     keyDumpParams = self.buildKvStoreKeyDumpParams(Consts.ADJ_DB_MARKER)
     publication = client.getKvStoreKeyValsFiltered(keyDumpParams)
     adjs_map = utils.adj_dbs_to_dict(publication, nodes, True,
                                      self.iter_publication)
     utils.print_adjs_table(adjs_map, self.enable_color, node, interface)
Пример #5
0
 def run(self, nodes, bidir, json):
     publication = self.client.dump_all_with_prefix(Consts.ADJ_DB_MARKER)
     adjs_map = utils.adj_dbs_to_dict(publication, nodes, bidir,
                                      self.iter_publication)
     if json:
         utils.print_adjs_json(adjs_map)
     else:
         utils.print_adjs_table(adjs_map, self.enable_color)
Пример #6
0
 def _run(self, client: OpenrCtrl.Client, nodes: set, bidir: bool,
          json: bool) -> None:
     adj_dbs = client.getDecisionAdjacencyDbs()
     adjs_map = utils.adj_dbs_to_dict(adj_dbs, nodes, bidir, self.iter_dbs)
     if json:
         utils.print_json(adjs_map)
     else:
         utils.print_adjs_table(adjs_map, self.enable_color, None, None)
Пример #7
0
 def _run(self, client: OpenrCtrl.Client, nodes: set, bidir: bool,
          json: bool) -> None:
     keyDumpParams = self.buildKvStoreKeyDumpParams(Consts.ADJ_DB_MARKER)
     publication = client.getKvStoreKeyValsFiltered(keyDumpParams)
     adjs_map = utils.adj_dbs_to_dict(publication, nodes, bidir,
                                      self.iter_publication)
     if json:
         utils.print_json(adjs_map)
     else:
         utils.print_adjs_table(adjs_map, self.enable_color)
Пример #8
0
    def _run(self, client: OpenrCtrl.Client, nodes: set, json: bool) -> None:
        adj_db = client.getLinkMonitorAdjacencies()

        # adj_dbs is built with ONLY one single (node, adjDb). Ignpre bidir option
        adjs_map = utils.adj_dbs_to_dict({adj_db.thisNodeName: adj_db}, nodes,
                                         False, self.iter_dbs)
        if json:
            utils.print_json(adjs_map)
        else:
            utils.print_adjs_table(adjs_map, None, None)
Пример #9
0
 def _run(self, client: OpenrCtrl.Client, nodes: set, bidir: bool,
          json: bool) -> None:
     adj_dbs = client.getDecisionAdjacencyDbs()
     adjs_map = utils.adj_dbs_to_dict(adj_dbs, nodes, bidir, self.iter_dbs)
     for _, val in adjs_map.items():
         for adj_entry in val["adjacencies"]:
             adj_entry["area"] = val.get("area", "N/A")
     if json:
         utils.print_json(adjs_map)
     else:
         utils.print_adjs_table(adjs_map, None, None)
Пример #10
0
    def _run(
        self,
        client: OpenrCtrl.Client,
        node: str,
        bidir: bool,
        output_file: str,
        edge_label: Any,
        json: bool,
    ) -> None:

        try:
            import matplotlib.pyplot as plt
            import networkx as nx
        except ImportError:
            print("Drawing topology requires `matplotlib` and `networkx` "
                  "libraries. You can install them with following command and "
                  "retry. \n"
                  "  pip install matplotlib\n"
                  "  pip install networkx")
            sys.exit(1)

        rem_str = {".facebook.com": "", ".tfbnw.net": ""}
        rem_str = dict((re.escape(k), v) for k, v in rem_str.items())
        rem_pattern = re.compile("|".join(rem_str.keys()))

        keyDumpParams = self.buildKvStoreKeyDumpParams(Consts.ADJ_DB_MARKER)
        publication = client.getKvStoreKeyValsFiltered(keyDumpParams)
        nodes = list(
            self.get_node_to_ips(client).keys()) if not node else [node]
        adjs_map = utils.adj_dbs_to_dict(publication, nodes, bidir,
                                         self.iter_publication)

        if json:
            return self.topology_json_dump(adjs_map.items())

        G = nx.Graph()
        adj_metric_map = {}
        node_overloaded = {}

        for this_node_name, db in adjs_map.items():
            node_overloaded[rem_pattern.sub(
                lambda m: rem_str[re.escape(m.group(0))],
                this_node_name)] = db["overloaded"]
            for adj in db["adjacencies"]:
                adj_metric_map[(this_node_name, adj["ifName"])] = adj["metric"]

        for this_node_name, db in adjs_map.items():
            for adj in db["adjacencies"]:
                adj["color"] = "r" if adj["isOverloaded"] else "b"
                adj["adjOtherIfMetric"] = adj_metric_map[(adj["otherNodeName"],
                                                          adj["otherIfName"])]
                G.add_edge(
                    rem_pattern.sub(lambda m: rem_str[re.escape(m.group(0))],
                                    this_node_name),
                    rem_pattern.sub(lambda m: rem_str[re.escape(m.group(0))],
                                    adj["otherNodeName"]),
                    **adj,
                )

        # hack to get nice fabric
        # XXX: FB Specific
        pos = {}
        eswx = 0
        sswx = 0
        fswx = 0
        rswx = 0
        blue_nodes = []
        red_nodes = []
        for node in G.nodes():
            if node_overloaded[node]:
                red_nodes.append(node)
            else:
                blue_nodes.append(node)

            if "esw" in node:
                pos[node] = [eswx, 3]
                eswx += 10
            elif "ssw" in node:
                pos[node] = [sswx, 2]
                sswx += 10
            elif "fsw" in node:
                pos[node] = [fswx, 1]
                fswx += 10
            elif "rsw" in node:
                pos[node] = [rswx, 0]
                rswx += 10

        maxswx = max(eswx, sswx, fswx, rswx)
        if maxswx > 0:
            # aesthetically pleasing multiplier (empirically determined)
            plt.figure(figsize=(maxswx * 0.5, 8))
        else:
            plt.figure(figsize=(min(len(G.nodes()) * 2, 150),
                                min(len(G.nodes()) * 2, 150)))
            pos = nx.spring_layout(G)
        plt.axis("off")

        edge_colors = []
        for _, _, d in G.edges(data=True):
            edge_colors.append(d["color"])

        nx.draw_networkx_nodes(G,
                               pos,
                               ax=None,
                               alpha=0.5,
                               node_color="b",
                               nodelist=blue_nodes)
        nx.draw_networkx_nodes(G,
                               pos,
                               ax=None,
                               alpha=0.5,
                               node_color="r",
                               nodelist=red_nodes)
        nx.draw_networkx_labels(G, pos, ax=None, alpha=0.5, font_size=8)
        nx.draw_networkx_edges(G,
                               pos,
                               ax=None,
                               alpha=0.5,
                               font_size=8,
                               edge_color=edge_colors)
        edge_labels = {}
        if node:
            if edge_label:
                edge_labels = {
                    (u, v): "<" + str(d["otherIfName"]) + ",  " +
                    str(d["metric"]) + " >     <" + str(d["ifName"]) + ", " +
                    str(d["adjOtherIfMetric"]) + ">"
                    for u, v, d in G.edges(data=True)
                }
            nx.draw_networkx_edge_labels(G,
                                         pos,
                                         edge_labels=edge_labels,
                                         font_size=6)

        print("Saving topology to file => {}".format(output_file))
        plt.savefig(output_file)
Пример #11
0
 def run(self, nodes, node, interface):
     publication = self.client.dump_all_with_filter(Consts.ADJ_DB_MARKER)
     adjs_map = utils.adj_dbs_to_dict(
         publication, nodes, True, self.iter_publication
     )
     utils.print_adjs_table(adjs_map, self.enable_color, node, interface)
Пример #12
0
    def run(self, node, bidir, output_file, edge_label):

        try:
            import matplotlib.pyplot as plt
            import networkx as nx
        except ImportError:
            print('Drawing topology requires `matplotlib` and `networkx` '
                  'libraries. You can install them with following command and '
                  'retry. \n'
                  '  pip install matplotlib\n'
                  '  pip install networkx')
            sys.exit(1)

        rem_str = {
            '.facebook.com': '',
            '.tfbnw.net': '',
        }
        rem_str = dict((re.escape(k), v) for k, v in rem_str.items())
        rem_pattern = re.compile("|".join(rem_str.keys()))

        publication = self.client.dump_all_with_prefix(Consts.ADJ_DB_MARKER)
        nodes = self.get_node_to_ips().keys() if not node else [node]
        adjs_map = utils.adj_dbs_to_dict(publication, nodes, bidir,
                                         self.iter_publication)
        G = nx.Graph()
        adj_metric_map = {}
        node_overloaded = {}

        for this_node_name, db in adjs_map.items():
            node_overloaded[rem_pattern.sub(lambda m:
                            rem_str[re.escape(m.group(0))],
                            this_node_name)] = db['overloaded']
            for adj in db['adjacencies']:
                adj_metric_map[(this_node_name, adj['ifName'])] = adj['metric']

        for this_node_name, db in adjs_map.items():
            for adj in db['adjacencies']:
                adj['color'] = 'r' if adj['isOverloaded'] else 'b'
                adj['adjOtherIfMetric'] = adj_metric_map[(adj['otherNodeName'],
                                                            adj['otherIfName'])]
                G.add_edge(rem_pattern.sub(lambda m:
                                            rem_str[re.escape(m.group(0))],
                                            this_node_name),
                                            rem_pattern.sub(lambda m:
                                                            rem_str[re.escape(m.group(0))],
                                                            adj['otherNodeName']), **adj)

        # hack to get nice fabric
        # XXX: FB Specific
        pos = {}
        eswx = 0
        sswx = 0
        fswx = 0
        rswx = 0
        blue_nodes = []
        red_nodes = []
        for node in G.nodes():
            if (node_overloaded[node]):
                red_nodes.append(node)
            else:
                blue_nodes.append(node)

            if 'esw' in node:
                pos[node] = [eswx, 3]
                eswx += 10
            elif 'ssw' in node:
                pos[node] = [sswx, 2]
                sswx += 10
            elif 'fsw' in node:
                pos[node] = [fswx, 1]
                fswx += 10
            elif 'rsw' in node:
                pos[node] = [rswx, 0]
                rswx += 10

        maxswx = max(eswx, sswx, fswx, rswx)
        if maxswx > 0:
            # aesthetically pleasing multiplier (empirically determined)
            plt.figure(figsize=(maxswx * 0.5, 8))
        else:
            plt.figure(figsize=(min(len(G.nodes()) * 2, 150),
                                min(len(G.nodes()) * 2, 150)))
            pos = nx.spring_layout(G)
        plt.axis('off')

        edge_colors = []
        for _, _, d in G.edges(data=True):
            edge_colors.append(d['color'])

        nx.draw_networkx_nodes(G, pos, ax=None, alpha=0.5,
                                node_color='b', nodelist=blue_nodes)
        nx.draw_networkx_nodes(G, pos, ax=None, alpha=0.5,
                                node_color='r', nodelist=red_nodes)
        nx.draw_networkx_labels(G, pos, ax=None, alpha=0.5, font_size=8)
        nx.draw_networkx_edges(G, pos, ax=None, alpha=0.5,
                                font_size=8, edge_color=edge_colors)
        edge_labels = {}
        if node:
            if edge_label:
                edge_labels = {(u, v): '<' + str(d['otherIfName']) + ',  ' +
                                str(d['metric']) +
                                ' >     <' + str(d['ifName']) +
                                ', ' + str(d['adjOtherIfMetric']) + '>'
                                for u, v, d in G.edges(data=True)}
            nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels,
                                         font_size=6)

        print('Saving topology to file => {}'.format(output_file))
        plt.savefig(output_file)
Пример #13
0
 def printAdjNode(self, publication, nodes, node, interface):
     adjs_map = utils.adj_dbs_to_dict(publication, nodes, True,
                                      self.iter_publication)
     utils.print_adjs_table(adjs_map, node, interface)