package org.opendaylight.netvirt.bgpmanager.oam;
-import javax.management.JMException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import java.io.*;
-import java.lang.management.ManagementFactory;
-import java.net.*;
-import java.util.*;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import org.opendaylight.netvirt.bgpmanager.BgpManager;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.annotation.Nonnull;
+import javax.inject.Inject;
+
+import org.opendaylight.infrautils.metrics.Counter;
+import org.opendaylight.infrautils.metrics.Labeled;
+import org.opendaylight.infrautils.metrics.MetricDescriptor;
+import org.opendaylight.infrautils.metrics.MetricProvider;
+import org.opendaylight.netvirt.bgpmanager.thrift.gen.af_afi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+@SuppressFBWarnings("DM_DEFAULT_ENCODING")
+public class BgpCounters implements Runnable, AutoCloseable {
+ public static final String BGP_VPNV6_FILE = "cmd_ip_bgp_vpnv6_all.txt";
+ public static final String BGP_VPNV4_FILE = "cmd_ip_bgp_vpnv4_all.txt";
+ public static final String BGP_EVPN_FILE = "cmd_bgp_l2vpn_evpn_all.txt";
+ public static final String BGP_VPNV6_SUMMARY_FILE = "cmd_ip_bgp_vpnv6_all_summary.txt";
+ public static final String BGP_VPNV4_SUMMARY_FILE = "cmd_ip_bgp_vpnv4_all_summary.txt";
+ public static final String BGP_EVPN_SUMMARY_FILE = "cmd_bgp_evpn_all_summary.txt";
-/**
- * Created by ECHIAPT on 8/4/2015.
- */
-public class BgpCounters extends TimerTask {
+ private static final Logger LOG = LoggerFactory.getLogger(BgpCounters.class);
+
+ private final Map<String, String> totalPfxMap = new ConcurrentHashMap<>();
- private static final Logger LOGGER = LoggerFactory.getLogger(BgpCounters.class);
- public static BgpCountersBroadcaster bgpStatsBroadcaster = null;
- public MBeanServer bgpStatsServer = null;
- public Map <String, String> countersMap = new HashMap<String, String>();
- private String bgpSdncMip = "127.0.0.1";
+ private final String bgpSdncMip;
+ private final MetricProvider metricProvider;
- public BgpCounters(String mipAddress) {
- bgpSdncMip = mipAddress;
+ @Inject
+ public BgpCounters(String mipAddress, final MetricProvider metricProvider) {
+ this.metricProvider = metricProvider;
+ this.bgpSdncMip = mipAddress;
+ }
+
+ @Override
+ public void close() {
}
@Override
- public void run () {
+ public void run() {
try {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Fetching counters from BGP at " + new Date());
- }
+ LOG.debug("Fetching counters from BGP");
resetCounters();
- fetchCmdOutputs("cmd_ip_bgp_summary.txt","show ip bgp summary");
+ fetchCmdOutputs("cmd_ip_bgp_summary.txt", "show ip bgp summary");
fetchCmdOutputs("cmd_bgp_ipv4_unicast_statistics.txt", "show bgp ipv4 unicast statistics");
- fetchCmdOutputs("cmd_ip_bgp_vpnv4_all.txt", "show ip bgp vpnv4 all");
- parse_ip_bgp_summary();
- parse_bgp_ipv4_unicast_statistics();
- parse_ip_bgp_vpnv4_all();
- if (LOGGER.isDebugEnabled()) {
- dumpCounters();
- }
- if (bgpStatsBroadcaster == null) {
- //First time execution
- try {
- bgpStatsBroadcaster = new BgpCountersBroadcaster();
- bgpStatsServer = ManagementFactory.getPlatformMBeanServer();
- ObjectName bgpStatsObj = new ObjectName("SDNC.PM:type=BgpCountersBroadcaster");
- bgpStatsServer.registerMBean(bgpStatsBroadcaster, bgpStatsObj);
- LOGGER.info("BGP Counters MBean Registered :::");
- } catch (JMException e) {
- LOGGER.error("Adding a NotificationBroadcaster failed." , e);
- return;
- }
- }
- bgpStatsBroadcaster.setBgpCountersMap(countersMap);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Finished updating the counters from BGP at " + new Date());
- }
- } catch (Exception e) {
- LOGGER.error("Failed to publish bgp counters ", e);
- }
- }
-
- public void dumpCounters () {
- Iterator<Map.Entry<String, String>> entries = countersMap.entrySet().iterator();
- while (entries.hasNext()) {
- Map.Entry<String, String> entry = entries.next();
- LOGGER.debug(entry.getKey() + ", Value = " + entry.getValue());
+ fetchCmdOutputs(BGP_VPNV4_FILE, "show ip bgp vpnv4 all");
+ fetchCmdOutputs(BGP_VPNV6_FILE, "show ip bgp vpnv6 all");
+ fetchCmdOutputs(BGP_EVPN_FILE, "show bgp l2vpn evpn all");
+ parseIpBgpSummary();
+ parseIpBgpVpnv4All();
+ parseIpBgpVpnv6All();
+ parseBgpL2vpnEvpnAll();
+ LOG.debug("Finished updating the counters from BGP");
+ } catch (IOException e) {
+ LOG.error("Failed to publish bgp counters ", e);
}
}
- public void fetchCmdOutputs (String filename, String cmdName) throws IOException {
- Socket socket;
- int serverPort = 2605;
- String serverName = bgpSdncMip;
- int sockTimeout = 2;
- PrintWriter out_to_socket;
- BufferedReader in_from_socket;
- char cbuf[] = new char[10];
- char op_buf[];
- StringBuilder sb = new StringBuilder();
- int ip, ret;
- StringBuilder temp;
- char ch, gt = '>', hash = '#';
- String vtyPassword = BgpConstants.QBGP_VTY_PASSWORD;
- String passwordCheckStr = "Password:";
- String enableString = "en";
- String prompt, replacedStr;
-
- try
- {
- socket = new Socket(serverName, serverPort);
-
- }
- catch (UnknownHostException ioe) {
- LOGGER.error("No host exists: " + ioe.getMessage());
- return;
- }
- catch (IOException ioe) {
- LOGGER.error("I/O error occured " + ioe.getMessage());
- return;
- }
- try {
- socket.setSoTimeout(sockTimeout*1000);
- out_to_socket = new PrintWriter(socket.getOutputStream(), true);
- in_from_socket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
-
- } catch (IOException ioe) {
- LOGGER.error("IOException thrown.");
- socket.close();
- return;
- }
- while (true) {
- try {
- ret = in_from_socket.read(cbuf);
- }
- catch (SocketTimeoutException ste) {
- LOGGER.error("Read from Socket timed Out while asking for password.");
- socket.close();
- return;
- }
- catch (IOException ioe) {
- LOGGER.error("Caught IOException");
- socket.close();
- return;
- }
- if (ret == -1) {
- LOGGER.error("Connection closed by BGPd.");
- socket.close();
- return;
- } else {
- sb.append(cbuf);
- if (sb.toString().contains(passwordCheckStr)) {
- break;
+ void fetchCmdOutputs(String filename, String cmdName) throws IOException {
+ try (Socket socket = new Socket(bgpSdncMip, 2605);
+ PrintWriter toRouter = new PrintWriter(socket.getOutputStream(), true);
+ BufferedReader fromRouter = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+ BufferedWriter toFile = new BufferedWriter(new FileWriter(filename, true))) {
+ socket.setSoTimeout(2 * 1000);
+
+ // Wait for the password prompt
+ StringBuilder sb = new StringBuilder();
+ int read;
+ char[] cbuf = new char[10];
+ while (!sb.toString().contains("Password:")) {
+ if ((read = fromRouter.read(cbuf)) == -1) {
+ LOG.error("Connection closed by BGPd.");
+ return;
}
+ sb.append(cbuf, 0, read);
}
- }
- sb.setLength(0);
- out_to_socket.println(vtyPassword);
-
- while (true) {
- try {
- ip = in_from_socket.read();
- }
- catch (SocketTimeoutException ste) {
- LOGGER.error(sb.toString());
- LOGGER.error("Read from Socket timed Out while verifying the password.");
- socket.close();
- return;
- }
- if (ip == (int)gt || ip == (int)hash) {
- break;
- } else if (ip == -1) {
- LOGGER.error(sb.toString());
- LOGGER.error("Connection closed by BGPd.");
- socket.close();
- return;
- } else {
- ch = (char)ip;
- sb.append(ch);
+ // Send the password
+ toRouter.println(BgpConstants.QBGP_VTY_PASSWORD);
+ // Wait for the prompt (ending with '>' or '#')
+ sb = new StringBuilder();
+ String prompt = null;
+ while (prompt == null) {
+ switch (read = fromRouter.read()) {
+ case -1:
+ LOG.error("Connection closed by BGPd, read {}", sb.toString());
+ return;
+ case '>':
+ // Fall through
+ case '#':
+ sb.append((char) read);
+ prompt = sb.toString().trim();
+ break;
+ default:
+ sb.append((char) read);
+ break;
+ }
}
- }
- prompt = sb.toString();
- prompt = prompt.trim();
- sb.setLength(0);
- out_to_socket.println(enableString);
+ // Enable
+ toRouter.println("en");
- while (true) {
- try {
- ip = in_from_socket.read();
- }
- catch (SocketTimeoutException ste) {
- LOGGER.error(sb.toString());
- LOGGER.error("Read from Socket timed Out while keying the en keyword.");
- socket.close();
- return;
+ // Wait for '#'
+ while ((read = fromRouter.read()) != '#') {
+ if (read == -1) {
+ LOG.error("Connection closed by BGPd, read {}", sb.toString());
+ return;
+ }
}
- if (ip == (int)hash) {
- break;
- } else if (ip == -1) {
- LOGGER.error(sb.toString());
- LOGGER.error("Connection closed by BGPd.");
- socket.close();
- return;
- } else {
- ch = (char)ip;
- sb.append(ch);
- }
- }
- sb.setLength(0);
- temp = new StringBuilder();
- File file;
- FileWriter fileWritter;
- BufferedWriter bufferWritter;
+ // Send the command
+ toRouter.println(cmdName);
- try {
- file = new File(filename);
- if (!file.exists()) {
- file.createNewFile();
- }
- fileWritter = new FileWriter(file.getName(), true);
- bufferWritter = new BufferedWriter(fileWritter);
- } catch (IOException e) {
- return;
- }
- out_to_socket.println(cmdName);
- temp.setLength(0);
- while (true) {
- try {
- op_buf = new char[100];
- ret = in_from_socket.read(op_buf);
-
- } catch (SocketTimeoutException ste) {
- break;
- } catch (SocketException soc) {
- break;
- } catch (IOException ioe) {
- ioe.printStackTrace();
- break;
+ // Read all the router's output
+ sb = new StringBuilder();
+ cbuf = new char[1024];
+ while ((read = fromRouter.read(cbuf)) != -1) {
+ sb.append(cbuf, 0, read);
+ if (sb.toString().trim().endsWith(prompt)) {
+ break;
+ }
}
- if (ret == -1) {
- break;
+ // Only keep output up to the last prompt
+ int lastPromptIndex = sb.lastIndexOf(prompt);
+ if (lastPromptIndex >= 0) {
+ sb.delete(lastPromptIndex, sb.length());
}
- temp.append(op_buf);
- }
- String outputStr = temp.toString();
- StringBuffer output = new StringBuffer();
-
- outputStr.replaceAll("^\\s+|\\s+$", "");
- output.append(outputStr);
- if (output.toString().trim().contains(prompt)) {
- int index = output.toString().lastIndexOf(prompt);
- String newString = output.toString().substring(0, index);
- output.setLength(0);
- output.append(newString);
- }
- try {
- bufferWritter.write(output.toString().trim());
- temp.setLength(0);
- } catch (IOException e) {
- e.printStackTrace();
- return;
- }
- try {
- bufferWritter.close();
- fileWritter.close();
- socket.close();
+ // Store in the file
+ toFile.write(sb.toString().trim());
+ } catch (UnknownHostException e) {
+ LOG.error("Unknown host {}", bgpSdncMip, e);
+ } catch (SocketTimeoutException e) {
+ LOG.error("Socket timeout", e);
} catch (IOException e) {
- e.printStackTrace();
- return;
+ LOG.error("I/O error", e);
}
}
- public static boolean validate(final String ip){
- if (ip == null || ip.equals("")) {
+ private static boolean validate(@Nonnull final String ip, af_afi afi) {
+ if (ip.equals("")) {
return false;
}
- final String PATTERN =
- "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
- Pattern pattern = Pattern.compile(PATTERN);
- Matcher matcher = pattern.matcher(ip);
- return matcher.matches();
+ int identifiedAFI = 0;
+ try {
+ InetAddress address = InetAddress.getByName(ip);
+ if (address instanceof Inet6Address) {
+ identifiedAFI = af_afi.AFI_IPV6.getValue();
+ } else if (address instanceof Inet4Address) {
+ identifiedAFI = af_afi.AFI_IP.getValue();
+ }
+ } catch (java.net.UnknownHostException e) {
+ /*if exception is catched then the prefix is not an IPv6 and IPv4*/
+ LOG.error("Unrecognized ip address ipAddress: {}", ip);
+ }
+ return identifiedAFI == afi.getValue() ? true : false;
}
-
/*
* The below function parses the output of "show ip bgp summary" saved in a file.
* Below is the snippet for the same :-
</output>
*/
- public void parse_ip_bgp_summary() {
+ private void parseIpBgpSummary() {
File file = new File("cmd_ip_bgp_summary.txt");
- Scanner scanner;
- String lineFromFile;
- List<String> inputStrs = new ArrayList<String>();
- int i = 0;
- String as,rx, tx;
- boolean startEntries = false;
- String[] result;
- String StrIP;
-
- try {
- scanner = new Scanner(file);
- } catch (IOException e) {
- LOGGER.error("Could not process the file " + file.getAbsolutePath());
- return ;
- }
- while (scanner.hasNextLine()) {
- lineFromFile = scanner.nextLine();
- inputStrs.add(lineFromFile);
- }
- String str;
- StringBuilder NbrInfoKey = new StringBuilder();
-
- while (i < inputStrs.size()) {
- str = inputStrs.get(i);
- if (str.contains("State/PfxRcd")) {
- startEntries = true;
- } else if (startEntries == true) {
- result = str.split("\\s+");
- try {
- StrIP = result[0].trim();
- if (!validate(StrIP)) {
+ try (Scanner scanner = new Scanner(file)) {
+ boolean startEntries = false;
+ while (scanner.hasNextLine()) {
+ String str = scanner.nextLine();
+ if (str.contains("State/PfxRcd")) {
+ startEntries = true;
+ } else if (startEntries) {
+ String[] result = str.split("\\s+");
+ if (result.length < 5) {
return;
}
- as = result[2];
- rx = result[3];
- tx = result[4];
-
- NbrInfoKey.setLength(0);
- NbrInfoKey.append(BgpConstants.BGP_COUNTER_NBR_PKTS_RX).append(":").
- append("BGP_Nbr_IP_").append(StrIP).append("_AS_").append(as).append("_PktsReceived");
- countersMap.put(NbrInfoKey.toString(), rx);
+ String strIp = result[0].trim();
+ if (!validate(strIp, af_afi.AFI_IP)) {
+ return;
+ }
+ final String as = result[2];
+ final String rx = result[3];
+ final String tx = result[4];
+ Counter counter = getCounter(BgpConstants.BGP_COUNTER_NBR_PKTS_RX, as,
+ rx, null, strIp, null);
+ updateCounter(counter, Long.parseLong(rx));
- NbrInfoKey.setLength(0);
- NbrInfoKey.append(BgpConstants.BGP_COUNTER_NBR_PKTS_TX).append(":").
- append("BGP_Nbr_IP_").append(StrIP).append("_AS_").append(as).append("_PktsSent");
- countersMap.put(NbrInfoKey.toString(), tx);
- } catch (Exception e) {
- return;
+ counter = getCounter(BgpConstants.BGP_COUNTER_NBR_PKTS_TX, as,
+ null, tx, strIp, null);
+ updateCounter(counter, Long.parseLong(tx));
}
}
- i++;
+ } catch (IOException e) {
+ LOG.error("Could not process the file {}", file.getAbsolutePath());
}
- }
- /*
- * The below function parses the output of "show bgp ipv4 unicast statistics" saved in a file.
- * Below is the sample output for the same :-
- <output>
- BGP IPv4 Unicast RIB statistics
- ...
- Total Prefixes : 8
- ......
- </output>
- */
-
- public void parse_bgp_ipv4_unicast_statistics() {
- File file = new File("cmd_bgp_ipv4_unicast_statistics.txt");
- Scanner scanner;
- String lineFromFile;
- StringBuilder key = new StringBuilder();
- String totPfx = "";
- List<String> inputStrs = new ArrayList<String>();
- try {
- scanner = new Scanner(file);
- } catch (IOException e) {
- System.err.println("Could not process the file " + file.getAbsolutePath());
- return ;
- }
- while (scanner.hasNextLine()) {
-
- lineFromFile = scanner.nextLine();
- inputStrs.add(lineFromFile);
- }
-
- int i = 0;
- String instr;
- while (i < inputStrs.size()) {
- instr = inputStrs.get(i);
- if (instr.contains("Total Prefixes")) {
- String[] result = instr.split(":");
- try {
- totPfx = result[1].trim();
- } catch (Exception e) {
- totPfx = "0";
- }
- break;
- }
- i++;
- }
- key.setLength(0);
- key.append(BgpConstants.BGP_COUNTER_TOTAL_PFX).append(":").
- append("Bgp_Total_Prefixes");
- countersMap.put(key.toString(), totPfx);
}
/*
*>i17.18.17.17/32 10.183.181.25 0 100 0 ?
</output>
*/
- public void parse_ip_bgp_vpnv4_all() {
- File file = new File("cmd_ip_bgp_vpnv4_all.txt");
- Scanner scanner;
- String lineFromFile;
- List<String> inputStrs = new ArrayList<String>();
+ private void parseIpBgpVpnv4All() {
+ File file = new File(BGP_VPNV4_FILE);
+ List<String> inputStrs = new ArrayList<>();
- try {
- scanner = new Scanner(file);
+ try (Scanner scanner = new Scanner(file)) {
+ while (scanner.hasNextLine()) {
+ inputStrs.add(scanner.nextLine());
+ }
} catch (IOException e) {
- System.err.println("Could not process the file " + file.getAbsolutePath());
- return ;
- }
- while (scanner.hasNextLine()) {
- lineFromFile = scanner.nextLine();
- inputStrs.add(lineFromFile);
+ LOG.error("Could not process the file {}", file.getAbsolutePath());
+ return;
}
- int i = 0;
- String instr, rd;
- while (i < inputStrs.size()) {
- instr = inputStrs.get(i);
+ for (int i = 0; i < inputStrs.size(); i++) {
+ String instr = inputStrs.get(i);
if (instr.contains("Route Distinguisher")) {
String[] result = instr.split(":");
- rd = result[1].trim() + "_" + result[2].trim();
- i = processRouteCount(rd, i + 1, inputStrs);
+ String rd = result[1].trim() + "_" + result[2].trim();
+ i = processRouteCount(rd + "_VPNV4", i + 1, inputStrs);
+ }
+ }
+ }
+ /*
+ * The below function parses the output of "show ip bgp vpnv6 all" saved in a file.
+ * Below is the sample output for the same :-
+ * show ip bgp vpnv6 all
+ <output>
+ BGP table version is 0, local router ID is 10.183.181.21
+ ......
+ Route Distinguisher: 100:1
+ *>i2001:db8:0:2::/128 10.183.181.25 0 100 0 ?
+ *>i2001:db8:0:2::/128 10.183.181.25 0 100 0 ?
+ *>i2001:db8:0:2::/128 10.183.181.25 0 100 0 ?
+ *>i2001:db8:0:2::/128 10.183.181.25 0 100 0 ?
+ Route Distinguisher: 100:2
+ *>i2001:db9:0:3::/128 10.183.181.25 0 100 0 ?
+ *>i2001:db9:0:3::/128 10.183.181.25 0 100 0 ?
+ *>i2001:db9:0:3::/128 10.183.181.25 0 100 0 ?
+ </output>
+ */
+ private void parseIpBgpVpnv6All() {
+ File file = new File(BGP_VPNV6_FILE);
+ List<String> inputStrs = new ArrayList<>();
+
+ try (Scanner scanner = new Scanner(file)) {
+ while (scanner.hasNextLine()) {
+ inputStrs.add(scanner.nextLine());
}
- i++;
+ } catch (IOException e) {
+ LOG.error("Could not process the file {}", file.getAbsolutePath());
+ return;
}
+ for (int i = 0; i < inputStrs.size(); i++) {
+ String instr = inputStrs.get(i);
+ if (instr.contains("Route Distinguisher")) {
+ String[] result = instr.split(":");
+ String rd = result[1].trim() + "_" + result[2].trim();
+ i = processRouteCount(rd + "_VPNV6", i + 1, inputStrs);
+ }
+ }
+ }
+
+ private void parseBgpL2vpnEvpnAll() {
+ File file = new File(BGP_EVPN_FILE);
+ List<String> inputStrs = new ArrayList<>();
+ try (Scanner scanner = new Scanner(file)) {
+ while (scanner.hasNextLine()) {
+ inputStrs.add(scanner.nextLine());
+ }
+ } catch (IOException e) {
+ LOG.error("Could not process the file {}", file.getAbsolutePath());
+ return;
+ }
+ for (int i = 0; i < inputStrs.size(); i++) {
+ String instr = inputStrs.get(i);
+ if (instr.contains("Route Distinguisher")) {
+ String[] result = instr.split(":");
+ String rd = result[1].trim() + "_" + result[2].trim();
+ i = processRouteCount(rd + "_EVPN", i + 1, inputStrs);
+ }
+ }
+ /*populate the "BgpTotalPrefixes" counter by combining
+ the prefixes that are calculated per RD basis*/
+ long bgpTotalPfxs = calculateBgpTotalPrefixes();
+ LOG.trace("BGP Total Prefixes:{}",bgpTotalPfxs);
+ Counter counter = getCounter(BgpConstants.BGP_COUNTER_TOTAL_PFX, null, null, null,
+ null, null);
+ updateCounter(counter, bgpTotalPfxs);
}
- public int processRouteCount(String rd, int startIndex, List<String> inputStrs) {
- int num = startIndex, route_count = 0;
- String str;
- StringBuilder key = new StringBuilder();
- str = inputStrs.get(num);
+ private int processRouteCount(String rd, int startIndex, List<String> inputStrs) {
+ int num = startIndex;
+ long routeCount = 0;
+
+ String bgpRdRouteCountKey = BgpConstants.BGP_COUNTER_RD_ROUTE_COUNT + rd;
+ Counter counter = getCounter(BgpConstants.BGP_COUNTER_RD_ROUTE_COUNT, null, null, null,
+ null, rd);
- while (str != null && !str.trim().equals("") &&
- num <inputStrs.size()) {
+ for (String str = inputStrs.get(num); str != null && !str.trim().equals("")
+ && num < inputStrs.size();
+ str = inputStrs.get(num)) {
if (str.contains("Route Distinguisher")) {
- key.setLength(0);
- key.append(BgpConstants.BGP_COUNTER_RD_ROUTE_COUNT).append(":").
- append("BGP_RD_").append(rd).append("_route_count");
- countersMap.put(key.toString(), Integer.toString(route_count));
+ totalPfxMap.put(bgpRdRouteCountKey, Long.toString(routeCount));
+ updateCounter(counter, routeCount);
return num - 1;
}
- route_count++;
+ routeCount++;
num++;
if (num == inputStrs.size()) {
break;
}
- str = inputStrs.get(num);
}
- if (route_count == 0) {
+ if (routeCount == 0) {
// Erroneous condition, should never happen.
// Implies that the file contains marker for RD without routes.
// will form an infinite loop if not broken
// by sending a big number back.
- return ~0;
+ return Integer.MAX_VALUE;
}
- key.setLength(0);
- key.append(BgpConstants.BGP_COUNTER_RD_ROUTE_COUNT).append(":").
- append("BGP_RD_").append(rd).append("_route_count");
- countersMap.put(key.toString(), Integer.toString(route_count));
+ updateCounter(counter, routeCount);
return num - 1;
}
- public void resetCounters() {
- countersMap.clear();
+ private Long calculateBgpTotalPrefixes() {
+ return totalPfxMap.entrySet().stream()
+ .map(Map.Entry::getValue).mapToLong(Long::parseLong).sum();
+ }
+
+ private void resetCounters() {
+ totalPfxMap.clear();
resetFile("cmd_ip_bgp_summary.txt");
resetFile("cmd_bgp_ipv4_unicast_statistics.txt");
- resetFile("cmd_ip_bgp_vpnv4_all.txt");
+ resetFile(BGP_VPNV4_FILE);
+ resetFile(BGP_VPNV6_FILE);
+ resetFile(BGP_EVPN_FILE);
}
- public static void resetFile(String fileName) {
- File fileHndl = (new File(fileName));
- PrintWriter writer;
- boolean success;
-
- success = fileHndl.delete();
- if (!success) {
- try {
- writer = new PrintWriter(fileHndl);
- writer.print("");
- writer.close();
- } catch (Exception e) {
- return;
+ static void resetFile(String fileName) {
+ File file = new File(fileName);
+ if (!file.delete()) {
+ try (PrintWriter pw = new PrintWriter(file)) {
+ pw.print("");
+ } catch (FileNotFoundException e) {
+ // Ignored
}
}
-
}
- public static Map<String, String> parse_ip_bgp_vpnv4_all_summary(Map<String, String> countMap) {
- File file = new File("cmd_ip_bgp_vpnv4_all_summary.txt");
- Scanner scanner;
- String lineFromFile;
- List<String> inputStrs = new ArrayList<String>();
- int i = 0;
- boolean startEntries = false;
- String[] result;
- String StrIP;
-
- try {
- scanner = new Scanner(file);
+ static Map<String, String> parseIpBgpVpnAllSummary(Map<String, String> countMap,
+ String cmdFile,
+ af_afi afi) {
+ File file = new File(cmdFile);
+
+ try (Scanner scanner = new Scanner(file)) {
+ boolean startEntries = false;
+ while (scanner.hasNextLine()) {
+ String str = scanner.nextLine();
+ LOG.trace("str is:: {}", str);
+ if (str.contains("State/PfxRcd")) {
+ startEntries = true;
+ } else if (startEntries) {
+ String[] result = str.split("\\s+");
+ if (result.length > 9) {
+ String strIp = result[0].trim();
+ LOG.trace("strIp " + strIp);
+
+ if (!validate(strIp, afi)) {
+ break;
+ }
+ String statePfxRcvd = result[9];
+ countMap.put(strIp, statePfxRcvd);
+ }
+ }
+ }
} catch (IOException e) {
- LOGGER.trace("Could not process the file " + file.getAbsolutePath());
+ LOG.trace("Could not process the file {}", file.getAbsolutePath());
return null;
}
- while (scanner.hasNextLine()) {
- lineFromFile = scanner.nextLine();
- inputStrs.add(lineFromFile);
+ return countMap;
+ }
+
+ static Map<String, String> parseIpBgpVpnv4AllSummary(Map<String, String> countMap) {
+ return BgpCounters.parseIpBgpVpnAllSummary(countMap,
+ BGP_VPNV4_SUMMARY_FILE,
+ af_afi.AFI_IP);
+ }
+
+ static Map<String, String> parseIpBgpVpnv6AllSummary(Map<String, String> countMap) {
+ return BgpCounters.parseIpBgpVpnAllSummary(countMap,
+ BGP_VPNV6_SUMMARY_FILE,
+ af_afi.AFI_IP);
+ }
+
+ static Map<String, String> parseBgpL2vpnEvpnAllSummary(Map<String, String> countMap) {
+ return BgpCounters.parseIpBgpVpnAllSummary(countMap,
+ BGP_EVPN_SUMMARY_FILE,
+ af_afi.AFI_IP);
+ }
+
+ /**
+ * This method updates Counter values.
+ * @param counter object of the Counter
+ * @param counterValue value of Counter
+ */
+ private void updateCounter(Counter counter, long counterValue) {
+ try {
+ /*Reset counter to zero*/
+ counter.decrement(counter.get());
+ /*Set counter to specified value*/
+ counter.increment(counterValue);
+ } catch (IllegalStateException e) {
+ LOG.error("Exception occured during updating the Counter {}", counter, e);
}
- String str;
- while (i < inputStrs.size()) {
- str = inputStrs.get(i);
- LOGGER.trace("str is:: {}", str);
- if (str.contains("State/PfxRcd")) {
- startEntries = true;
- } else if (startEntries == true) {
- result = str.split("\\s+");
- try {
- StrIP = result[0].trim();
- LOGGER.trace("strIP " + StrIP);
-
- if (!validate(StrIP)) {
- break;
- }
- String state_pfxRcvd = result[9];
- countMap.put(StrIP, state_pfxRcvd);
- } catch (Exception e) {
- LOGGER.trace("Exception {} caught while processing ip bgp vpnv4 all summary command output, e");
- i++;
- continue;
- }
- }
- i++;
+ }
+
+ /**
+ * Returns the counter.
+ * This method returns counter and also creates counter if does not exist.
+ *
+ * @param counterName name of the counter.
+ * @param asValue as value.
+ * @param rxValue rx value.
+ * @param txValue tx value.
+ * @param neighborIp neighbor Ipaddress.
+ * @param rdValue rd value.
+ * @return counter object.
+ */
+ private Counter getCounter(String counterName, String asValue,
+ String rxValue, String txValue, String neighborIp, String rdValue) {
+ String counterTypeEntityCounter = "entitycounter";
+ String labelKeyEntityType = "entitytype";
+
+ String labelValEntityTypeBgpPeer = "bgp-peer";
+ String labelKeyAsId = "asid";
+ String labelKeyNeighborIp = "neighborip";
+
+ String labelValEntityTypeBgpRd = "bgp-rd";
+ String labelKeyRd = "rd";
+
+ String counterTypeAggregateCounter = "aggregatecounter";
+ String labelKeyCounterName = "name";
+
+ Counter counter = null;
+
+ if (rxValue != null) {
+ /*
+ * Following is the key pattern for Counter BgpNeighborPacketsReceived
+ * netvirt.bgpmanager.entitycounter{entitytype=bgp-peer, asid=value, neighborip=value, name=countername}
+ * */
+ Labeled<Labeled<Labeled<Labeled<Counter>>>> labeledCounter =
+ metricProvider.newCounter(MetricDescriptor.builder().anchor(this).project("netvirt")
+ .module("bgpmanager").id(counterTypeEntityCounter).build(),
+ labelKeyEntityType, labelKeyAsId,
+ labelKeyNeighborIp, labelKeyCounterName);
+ counter = labeledCounter.label(labelValEntityTypeBgpPeer).label(asValue)
+ .label(neighborIp).label(counterName);
+ } else if (txValue != null) {
+ /*
+ * Following is the key pattern for Counter BgpNeighborPacketsSent
+ * netvirt.bgpmanager.entitycounter{entitytype=bgp-peer, asid=value, neighborip=value, name=countername}
+ * */
+ Labeled<Labeled<Labeled<Labeled<Counter>>>> labeledCounter =
+ metricProvider.newCounter(MetricDescriptor.builder().anchor(this).project("netvirt")
+ .module("bgpmanager").id(counterTypeEntityCounter).build(),
+ labelKeyEntityType, labelKeyAsId,
+ labelKeyNeighborIp, labelKeyCounterName);
+ counter = labeledCounter.label(labelValEntityTypeBgpPeer).label(asValue)
+ .label(neighborIp).label(counterName);
+ } else if (rdValue != null) {
+ /*
+ * Following is the key pattern for Counter BgpRdRouteCount
+ * netvirt.bgpmanager.entitycounter{entitytype=bgp-rd, rd=value, name=countername}
+ * */
+ Labeled<Labeled<Labeled<Counter>>> labeledCounter =
+ metricProvider.newCounter(MetricDescriptor.builder().anchor(this).project("netvirt")
+ .module("bgpmanager").id(counterTypeEntityCounter).build(),
+ labelKeyEntityType, labelKeyRd,
+ labelKeyCounterName);
+ counter = labeledCounter.label(labelValEntityTypeBgpRd).label(rdValue)
+ .label(counterName);
+ } else {
+ /*
+ * Following is the key pattern for Counter BgpTotalPrefixes:Bgp_Total_Prefixes
+ * netvirt.bgpmanager.aggregatecounter{name=countername}
+ * */
+ Labeled<Counter> labeledCounter =
+ metricProvider.newCounter(MetricDescriptor.builder().anchor(this).project("netvirt")
+ .module("bgpmanager").id(counterTypeAggregateCounter).build(),
+ labelKeyCounterName);
+ counter = labeledCounter.label(counterName);
}
- return countMap;
+ return counter;
}
}