def _run(self, client: OpenrCtrl.Client, node_name: str) -> None: area = self.get_area_id() key = Consts.STATIC_PREFIX_ALLOC_PARAM_KEY # Retrieve previous allocation resp = None if area is None: resp = client.getKvStoreKeyVals([key]) else: resp = client.getKvStoreKeyValsArea([key], area) allocs = None if key in resp.keyVals: allocs = serializer.deserialize_thrift_object( resp.keyVals.get(key).value, alloc_types.StaticAllocation ) else: allocs = alloc_types.StaticAllocation(nodePrefixes={node_name: ""}) # Return if there need no change if node_name not in allocs.nodePrefixes: print("No changes needed. {}'s prefix is not set".format(node_name)) return # Update value in KvStore del allocs.nodePrefixes[node_name] value = serializer.serialize_thrift_object(allocs) super(AllocationsUnsetCmd, self)._run( client, key, value, "breeze", None, Consts.CONST_TTL_INF )
def toggle_link_overload_bit( self, client: OpenrCtrl.Client, overload: bool, interface: str, yes: bool = False, ) -> None: links = client.getInterfaces() print() if interface not in links.interfaceDetails: print("No such interface: {}".format(interface)) return if overload and links.interfaceDetails[interface].isOverloaded: print("Interface is already overloaded.\n") sys.exit(0) if not overload and not links.interfaceDetails[interface].isOverloaded: print("Interface is not overloaded.\n") sys.exit(0) action = "set overload bit" if overload else "unset overload bit" question_str = "Are you sure to {} for interface {} ?" if not utils.yesno(question_str.format(action, interface), yes): print() return if overload: client.setInterfaceOverload(interface) else: client.unsetInterfaceOverload(interface) print("Successfully {} for the interface.\n".format(action))
def toggle_node_overload_bit( self, client: OpenrCtrl.Client, overload: bool, yes: bool = False ) -> None: links = client.getInterfaces() host = links.thisNodeName print() if overload and links.isOverloaded: print("Node {} is already overloaded.\n".format(host)) sys.exit(0) if not overload and not links.isOverloaded: print("Node {} is not overloaded.\n".format(host)) sys.exit(0) action = "set overload bit" if overload else "unset overload bit" if not utils.yesno( "Are you sure to {} for node {} ?".format(action, host), yes ): print() return if overload: client.setNodeOverload() else: client.unsetNodeOverload() print("Successfully {}..\n".format(action))
def _run(self, client: OpenrCtrl.Client, nodes: set) -> None: area = self.get_area_id() all_nodes_to_ips = self.get_node_to_ips(client, area) if nodes: nodes = set(nodes.strip().split(",")) if "all" in nodes: nodes = list(all_nodes_to_ips.keys()) host_id = client.getMyNodeName() if host_id in nodes: nodes.remove(host_id) keyDumpParams = self.buildKvStoreKeyDumpParams(Consts.ALL_DB_MARKER) pub = None if not self.area_feature: pub = client.getKvStoreKeyValsFiltered(keyDumpParams) else: pub = client.getKvStoreKeyValsFilteredArea(keyDumpParams, area) kv_dict = self.dump_nodes_kvs(nodes, all_nodes_to_ips, area) for node in kv_dict: self.compare(pub.keyVals, kv_dict[node], host_id, node) else: nodes = list(all_nodes_to_ips.keys()) kv_dict = self.dump_nodes_kvs(nodes, all_nodes_to_ips, area) for our_node, other_node in combinations(kv_dict.keys(), 2): self.compare( kv_dict[our_node], kv_dict[other_node], our_node, other_node )
def _run(self, client: OpenrCtrl.Client) -> None: if not self.area_feature: super()._run(client) return all_kv = kv_store_types.Publication() all_kv.keyVals = {} node_area = {} nodes = set() for area in self.areas: prefix_keys = client.getKvStoreKeyValsFilteredArea( self.buildKvStoreKeyDumpParams(Consts.PREFIX_DB_MARKER), area ) all_kv.keyVals.update(prefix_keys.keyVals) adj_keys = client.getKvStoreKeyValsFilteredArea( self.buildKvStoreKeyDumpParams(Consts.ADJ_DB_MARKER), area ) host_id = client.getMyNodeName() node_set = self.get_connected_nodes(adj_keys, host_id) # save area associated with each node for node in node_set: node_area[node] = area nodes.update(node_set) self.print_kvstore_nodes(nodes, all_kv, host_id, node_area)
def _run(self, client: OpenrCtrl.Client, node_name: str, prefix_str: str) -> None: area = self.get_area_id() key = Consts.STATIC_PREFIX_ALLOC_PARAM_KEY # Retrieve previous allocation resp = None if area is None: resp = client.getKvStoreKeyVals([key]) else: resp = client.getKvStoreKeyValsArea([key], area) allocs = None if key in resp.keyVals: allocs = serializer.deserialize_thrift_object( resp.keyVals.get(key).value, alloc_types.StaticAllocation ) else: allocs = alloc_types.StaticAllocation(nodePrefixes={}) # Return if there is no change prefix = ipnetwork.ip_str_to_prefix(prefix_str) if allocs.nodePrefixes.get(node_name) == prefix: print( "No changes needed. {}'s prefix is already set to {}".format( node_name, prefix_str ) ) return # Update value in KvStore allocs.nodePrefixes[node_name] = prefix value = serializer.serialize_thrift_object(allocs) super(AllocationsSetCmd, self)._run( client, key, value, "breeze", None, Consts.CONST_TTL_INF )
def _run( self, client: OpenrCtrl.Client, prefixes: List[str], prefix_type: str ) -> None: tprefixes = self.to_thrift_prefixes( prefixes, self.to_thrift_prefix_type(prefix_type) ) client.withdrawPrefixes(tprefixes) print(f"Withdrew {len(prefixes)} prefixes")
def _run(self, client: OpenrCtrl.Client, yes: bool = False) -> None: question_str = "Are you sure to force sending GR msg to neighbors?" if not utils.yesno(question_str, yes): print() return client.floodRestartingMsg() print("Successfully forcing to send GR msgs.\n")
def _run(self, client: OpenrCtrl.Client) -> None: prefix_keys = client.getKvStoreKeyValsFiltered( self.buildKvStoreKeyDumpParams(Consts.PREFIX_DB_MARKER)) adj_keys = client.getKvStoreKeyValsFiltered( self.buildKvStoreKeyDumpParams(Consts.ADJ_DB_MARKER)) host_id = client.getMyNodeName() self.print_kvstore_nodes(self.get_connected_nodes(adj_keys, host_id), prefix_keys, host_id)
def _run( self, client: OpenrCtrl.Client, node: str, interface: str, metric: str, yes: bool, ) -> None: client.setAdjacencyMetric(interface, node, int(metric))
def _run(self, client: OpenrCtrl.Client, json_opt: bool = False) -> None: try: resp = client.getEventLogs() self.print_log_data(resp, json_opt) except TypeError: host_id = client.getMyNodeName() print( "Incompatible return type. Please upgrade Open/R binary on {}". format(host_id))
def get_dbs(self, client: OpenrCtrl.Client) -> Tuple[Dict, Dict, Dict]: # get LSDB from Decision decision_adj_dbs = client.getDecisionAdjacencyDbs() decision_prefix_dbs = client.getDecisionPrefixDbs() # get LSDB from KvStore kvstore_keyvals = client.getKvStoreKeyValsFiltered( kv_store_types.KeyDumpParams(Consts.ALL_DB_MARKER)).keyVals return (decision_adj_dbs, decision_prefix_dbs, kvstore_keyvals)
def _run( self, client: OpenrCtrl.Client, node: str, interface: str, yes: bool, *args, **kwargs, ) -> None: client.unsetAdjacencyMetric(interface, node)
def _run( self, client: OpenrCtrl.Client, prefixes: List[str], prefix_type: str, forwarding_type: str, ) -> None: tprefix_type = self.to_thrift_prefix_type(prefix_type) tprefixes = self.to_thrift_prefixes( prefixes, tprefix_type, self.to_thrift_forwarding_type(forwarding_type)) client.syncPrefixesByType(tprefix_type, tprefixes) print(f"Synced {len(prefixes)} prefixes with type {prefix_type}")
def _run(self, client: OpenrCtrl.Client, prefix: str) -> None: area = self.get_area_id() keyDumpParams = self.buildKvStoreKeyDumpParams(prefix) resp = None if area is None: resp = client.getKvStoreHashFiltered(keyDumpParams) else: resp = client.getKvStoreHashFilteredArea(keyDumpParams, area) signature = hashlib.sha256() for _, value in sorted(resp.keyVals.items(), key=lambda x: x[0]): signature.update(str(value.hash).encode("utf-8")) print("sha256: {}".format(signature.hexdigest()))
def _run( self, client: OpenrCtrl.Client, prefixes: List[str], prefix_type: str, forwarding_type: str, ) -> None: tprefixes = self.to_thrift_prefixes( prefixes, self.to_thrift_prefix_type(prefix_type), self.to_thrift_forwarding_type(forwarding_type), ) client.advertisePrefixes(tprefixes) print(f"Advertised {len(prefixes)} prefixes with type {prefix_type}")
def _run(self, client: OpenrCtrl.Client, json: bool) -> None: openr_version = client.getOpenrVersion() build_info = client.getBuildInfo() if json: if build_info.buildPackageName: info = utils.thrift_to_dict(build_info) print(utils.json_dumps(info)) version = utils.thrift_to_dict(openr_version) print(utils.json_dumps(version)) else: if build_info.buildPackageName: print("Build Information") print(" Built by: {}".format(build_info.buildUser)) print(" Built on: {}".format(build_info.buildTime)) print(" Built at: {}".format(build_info.buildHost)) print(" Build path: {}".format(build_info.buildPath)) print(" Package Name: {}".format(build_info.buildPackageName)) print(" Package Version: {}".format(build_info.buildPackageVersion)) print(" Package Release: {}".format(build_info.buildPackageRelease)) print(" Build Revision: {}".format(build_info.buildRevision)) print( " Build Upstream Revision: {}".format( build_info.buildUpstreamRevision ) ) print(" Build Platform: {}".format(build_info.buildPlatform)) print( " Build Rule: {} ({}, {}, {})".format( build_info.buildRule, build_info.buildType, build_info.buildTool, build_info.buildMode, ) ) rows = [] rows.append(["Open Source Version", ":", openr_version.version]) rows.append( [ "Lowest Supported Open Source Version", ":", openr_version.lowestSupportedVersion, ] ) print( printing.render_horizontal_table( rows, column_labels=[], tablefmt="plain" ) )
def _run(self, client: OpenrCtrl.Client, prefix_or_ip: List[str], json: bool) -> None: unicast_route_list = client.getUnicastRoutesFiltered(prefix_or_ip) host_name = client.getMyNodeName() if json: routes = { "unicastRoutes": [utils.unicast_route_to_dict(r) for r in unicast_route_list] } route_dict = {host_name: routes} utils.print_routes_json(route_dict) else: utils.print_unicast_routes( "Unicast Routes for {}".format(host_name), unicast_route_list)
def _run(self, client: OpenrCtrl.Client, labels: List[int], json: bool) -> None: int_label_filters = [int(label) for label in labels] mpls_route_list = client.getMplsRoutesFiltered(int_label_filters) host_name = client.getMyNodeName() if json: routes = { "mplsRoutes": [utils.mpls_route_to_dict(r) for r in mpls_route_list] } route_dict = {host_name: routes} utils.print_routes_json(route_dict) else: utils.print_mpls_routes( "MPLS Routes for {}".format(host_name), mpls_route_list )
def get_dbs(self, client: OpenrCtrl.Client, area: str) -> Tuple[Dict, Dict, Dict]: # get LSDB from Decision decision_adj_dbs = client.getDecisionAdjacencyDbs() decision_prefix_dbs = client.getDecisionPrefixDbs() area = utils.get_area_id(client, area) # get LSDB from KvStore params = openr_types.KeyDumpParams(Consts.ALL_DB_MARKER) params.keys = [Consts.ALL_DB_MARKER] if area is None: kvstore_keyvals = client.getKvStoreKeyValsFiltered(params).keyVals else: kvstore_keyvals = client.getKvStoreKeyValsFilteredArea(params, area).keyVals return (decision_adj_dbs, decision_prefix_dbs, kvstore_keyvals)
def _run( self, client: OpenrCtrl.Client, ) -> None: # Get data self.render(client.getOriginatedPrefixes())
def _run(self, client: OpenrCtrl.Client) -> None: key = Consts.STATIC_PREFIX_ALLOC_PARAM_KEY resp = client.getKvStoreKeyVals([key]) if key not in resp.keyVals: print("Static allocation is not set in KvStore") else: utils.print_allocations_table(resp.keyVals.get(key).value)
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)
def _run(self, client: OpenrCtrl.Client, nodes: Any, json: bool) -> None: keyDumpParams = self.buildKvStoreKeyDumpParams(Consts.PREFIX_DB_MARKER) resp = client.getKvStoreKeyValsFiltered(keyDumpParams) if json: utils.print_prefixes_json(resp, nodes, self.iter_publication) else: utils.print_prefixes_table(resp, nodes, self.iter_publication)
def _run(self, client: OpenrCtrl.Client, only_suppressed: bool, json: bool) -> None: links = client.getInterfaces() if only_suppressed: links.interfaceDetails = { k: v for k, v in links.interfaceDetails.items() if v.linkFlapBackOffMs } if json: self.print_links_json(links) else: if self.enable_color: overload_color = "red" if links.isOverloaded else "green" overload_status = click.style( "{}".format("YES" if links.isOverloaded else "NO"), fg=overload_color, ) caption = "Node Overload: {}".format(overload_status) self.print_links_table( links.interfaceDetails, caption, self.enable_color ) else: caption = "Node Overload: {}".format( "YES" if links.isOverloaded else "NO" ) self.print_links_table( links.interfaceDetails, caption, self.enable_color )
def _run(self, client: OpenrCtrl.Client, src: str, dst: str, max_hop: int) -> None: if not src or not dst: host_id = client.getMyNodeName() src = src or host_id dst = dst or host_id # Get prefix_dbs from KvStore self.prefix_dbs: Dict[str, lsdb_types.PrefixDatabase] = {} pub = client.getKvStoreKeyValsFiltered( kv_store_types.KeyDumpParams(Consts.PREFIX_DB_MARKER) ) for value in pub.keyVals.values(): utils.parse_prefix_database("", "", self.prefix_dbs, value) paths = self.get_paths(client, src, dst, max_hop) self.print_paths(paths)
def _run(self, client: OpenrCtrl.Client, file: str): running_conf = client.getRunningConfig() try: file_conf = client.dryrunConfig(file) except OpenrError as ex: click.echo(click.style("FAILED: {}".format(ex), fg="red")) return res = jsondiff.diff(running_conf, file_conf, load=True, syntax="explicit") if res: click.echo(click.style("DIFF FOUND!", fg="red")) print("== diff(running_conf, {}) ==".format(file)) print(res) else: click.echo(click.style("SAME", fg="green"))
def fetch( self, client: OpenrCtrl.Client, prefixes: List[str], node: Optional[str], area: Optional[str], ) -> List[ctrl_types.AdvertisedRouteDetail]: """ Fetch the requested data """ # Create filter route_filter = ctrl_types.ReceivedRouteFilter() if prefixes: route_filter.prefixes = [ ipnetwork.ip_str_to_prefix(p) for p in prefixes ] if node: route_filter.nodeName = node if area: route_filter.areaName = area # Get routes # pyre-fixme[7]: Expected `List[ctrl_types.AdvertisedRouteDetail]` but got # `List[ctrl_types.ReceivedRouteDetail]`. return client.getReceivedRoutesFiltered(route_filter)
def _run(self, client: OpenrCtrl.Client): policy = None try: policy = client.getRibPolicy() except ctrl_types.OpenrError as e: print(f"Error: {e.message}", file=sys.stderr) return # Convert the prefixes to readable format assert policy is not None for stmt in policy.statements: if stmt.matcher.prefixes: stmt.matcher.prefixes = [ ipnetwork.sprint_prefix(p) for p in stmt.matcher.prefixes ] # NOTE: We don't do explicit effor to print policy in print("> RibPolicy") print(f" Validity: {policy.ttl_secs}s") for stmt in policy.statements: prefixes = stmt.matcher.prefixes or [] action = stmt.action.set_weight or ctrl_types.RibRouteActionWeight( ) print(f" Statement: {stmt.name}") print(f" Prefix Match List: {', '.join(prefixes)}") print(" Action Set Weight:") print(f" Default: {action.default_weight}") print(" Area:") for area, weight in action.area_to_weight.items(): print(f" {area}: {weight}") print(" Neighbor:") for neighbor, weight in action.neighbor_to_weight.items(): print(f" {neighbor}: {weight}")
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)