2 * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netvirt.bgpmanager.oam;
11 import javax.management.JMException;
12 import javax.management.MBeanServer;
13 import javax.management.ObjectName;
15 import java.lang.management.ManagementFactory;
18 import java.util.regex.Matcher;
19 import java.util.regex.Pattern;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
25 * Created by ECHIAPT on 8/4/2015.
27 public class BgpCounters extends TimerTask {
29 private static final Logger LOGGER = LoggerFactory.getLogger(BgpCounters.class);
30 public static BgpCountersBroadcaster bgpStatsBroadcaster = null;
31 public MBeanServer bgpStatsServer = null;
32 public Map <String, String> countersMap = new HashMap<String, String>();
37 if (LOGGER.isDebugEnabled()) {
38 LOGGER.debug("Fetching counters from BGP at " + new Date());
41 fetchCmdOutputs("cmd_ip_bgp_summary.txt","show ip bgp summary");
42 fetchCmdOutputs("cmd_bgp_ipv4_unicast_statistics.txt", "show bgp ipv4 unicast statistics");
43 fetchCmdOutputs("cmd_ip_bgp_vpnv4_all.txt", "show ip bgp vpnv4 all");
44 parse_ip_bgp_summary();
45 parse_bgp_ipv4_unicast_statistics();
46 parse_ip_bgp_vpnv4_all();
47 if (LOGGER.isDebugEnabled()) {
50 if (bgpStatsBroadcaster == null) {
51 //First time execution
53 bgpStatsBroadcaster = new BgpCountersBroadcaster();
54 bgpStatsServer = ManagementFactory.getPlatformMBeanServer();
55 ObjectName bgpStatsObj = new ObjectName("SDNC.PM:type=BgpCountersBroadcaster");
56 bgpStatsServer.registerMBean(bgpStatsBroadcaster, bgpStatsObj);
57 LOGGER.info("BGP Counters MBean Registered :::");
58 } catch (JMException e) {
59 LOGGER.error("Adding a NotificationBroadcaster failed." , e);
63 bgpStatsBroadcaster.setBgpCountersMap(countersMap);
64 if (LOGGER.isDebugEnabled()) {
65 LOGGER.debug("Finished updating the counters from BGP at " + new Date());
67 } catch (Exception e) {
68 LOGGER.error("Failed to publish bgp counters ", e);
72 public void dumpCounters () {
73 Iterator<Map.Entry<String, String>> entries = countersMap.entrySet().iterator();
74 while (entries.hasNext()) {
75 Map.Entry<String, String> entry = entries.next();
76 LOGGER.debug(entry.getKey() + ", Value = " + entry.getValue());
80 public static void fetchCmdOutputs (String filename, String cmdName) throws IOException {
82 int serverPort = 2605;
83 String serverName = BgpConstants.DEFAULT_BGP_HOST_NAME;
85 PrintWriter out_to_socket;
86 BufferedReader in_from_socket;
87 char cbuf[] = new char[10];
89 StringBuilder sb = new StringBuilder();
92 char ch, gt = '>', hash = '#';
93 String vtyPassword = BgpConstants.QBGP_VTY_PASSWORD;
94 String passwordCheckStr = "Password:";
95 String enableString = "en";
96 String prompt, replacedStr;
100 socket = new Socket(serverName, serverPort);
103 catch (UnknownHostException ioe) {
104 LOGGER.error("No host exists: " + ioe.getMessage());
107 catch (IOException ioe) {
108 LOGGER.error("I/O error occured " + ioe.getMessage());
112 socket.setSoTimeout(sockTimeout*1000);
113 out_to_socket = new PrintWriter(socket.getOutputStream(), true);
114 in_from_socket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
116 } catch (IOException ioe) {
117 LOGGER.error("IOException thrown.");
123 ret = in_from_socket.read(cbuf);
125 catch (SocketTimeoutException ste) {
126 LOGGER.error("Read from Socket timed Out while asking for password.");
130 catch (IOException ioe) {
131 LOGGER.error("Caught IOException");
136 LOGGER.error("Connection closed by BGPd.");
141 if (sb.toString().contains(passwordCheckStr)) {
148 out_to_socket.println(vtyPassword);
152 ip = in_from_socket.read();
154 catch (SocketTimeoutException ste) {
155 LOGGER.error(sb.toString());
156 LOGGER.error("Read from Socket timed Out while verifying the password.");
162 } else if (ip == -1) {
163 LOGGER.error(sb.toString());
164 LOGGER.error("Connection closed by BGPd.");
174 prompt = sb.toString();
175 prompt = prompt.trim();
177 out_to_socket.println(enableString);
181 ip = in_from_socket.read();
183 catch (SocketTimeoutException ste) {
184 LOGGER.error(sb.toString());
185 LOGGER.error("Read from Socket timed Out while keying the en keyword.");
189 if (ip == (int)hash) {
191 } else if (ip == -1) {
192 LOGGER.error(sb.toString());
193 LOGGER.error("Connection closed by BGPd.");
203 temp = new StringBuilder();
205 FileWriter fileWritter;
206 BufferedWriter bufferWritter;
209 file = new File(filename);
210 if (!file.exists()) {
211 file.createNewFile();
213 fileWritter = new FileWriter(file.getName(), true);
214 bufferWritter = new BufferedWriter(fileWritter);
215 } catch (IOException e) {
218 out_to_socket.println(cmdName);
222 op_buf = new char[100];
223 ret = in_from_socket.read(op_buf);
225 } catch (SocketTimeoutException ste) {
227 } catch (SocketException soc) {
229 } catch (IOException ioe) {
230 ioe.printStackTrace();
239 String outputStr = temp.toString();
240 StringBuffer output = new StringBuffer();
242 outputStr.replaceAll("^\\s+|\\s+$", "");
243 output.append(outputStr);
244 if (output.toString().trim().contains(prompt)) {
245 int index = output.toString().lastIndexOf(prompt);
246 String newString = output.toString().substring(0, index);
248 output.append(newString);
251 bufferWritter.write(output.toString().trim());
253 } catch (IOException e) {
258 bufferWritter.close();
262 } catch (IOException e) {
268 public boolean validate(final String ip){
269 if (ip == null || ip.equals("")) {
272 final String PATTERN =
273 "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
274 Pattern pattern = Pattern.compile(PATTERN);
275 Matcher matcher = pattern.matcher(ip);
276 return matcher.matches();
281 * The below function parses the output of "show ip bgp summary" saved in a file.
282 * Below is the snippet for the same :-
284 BGP router identifier 10.183.254.53, local AS number 101
286 Neighbor V AS MsgRcvd MsgSent TblVer InQ OutQ Up/Down State/PfxRcd
287 10.183.254.76 4 100 3 4 0 0 0 00:01:27 0
289 Total number of neighbors 1
293 public void parse_ip_bgp_summary() {
294 File file = new File("cmd_ip_bgp_summary.txt");
297 List<String> inputStrs = new ArrayList<String>();
300 boolean startEntries = false;
305 scanner = new Scanner(file);
306 } catch (IOException e) {
307 LOGGER.error("Could not process the file " + file.getAbsolutePath());
310 while (scanner.hasNextLine()) {
312 lineFromFile = scanner.nextLine();
313 inputStrs.add(lineFromFile);
316 StringBuilder NbrInfoKey = new StringBuilder();
318 while (i < inputStrs.size()) {
319 str = inputStrs.get(i);
320 if (str.contains("State/PfxRcd")) {
322 } else if (startEntries == true) {
323 result = str.split("\\s+");
325 StrIP = result[0].trim();
326 if (!validate(StrIP)) {
333 NbrInfoKey.setLength(0);
334 NbrInfoKey.append(BgpConstants.BGP_COUNTER_NBR_PKTS_RX).append(":").
335 append("BGP_Nbr_IP_").append(StrIP).append("_AS_").append(as).append("_PktsReceived");
336 countersMap.put(NbrInfoKey.toString(), rx);
339 NbrInfoKey.setLength(0);
340 NbrInfoKey.append(BgpConstants.BGP_COUNTER_NBR_PKTS_TX).append(":").
341 append("BGP_Nbr_IP_").append(StrIP).append("_AS_").append(as).append("_PktsSent");
342 countersMap.put(NbrInfoKey.toString(), tx);
343 } catch (Exception e) {
351 * The below function parses the output of "show bgp ipv4 unicast statistics" saved in a file.
352 * Below is the sample output for the same :-
354 BGP IPv4 Unicast RIB statistics
361 public void parse_bgp_ipv4_unicast_statistics() {
362 File file = new File("cmd_bgp_ipv4_unicast_statistics.txt");
365 StringBuilder key = new StringBuilder();
367 List<String> inputStrs = new ArrayList<String>();
369 scanner = new Scanner(file);
370 } catch (IOException e) {
371 System.err.println("Could not process the file " + file.getAbsolutePath());
374 while (scanner.hasNextLine()) {
376 lineFromFile = scanner.nextLine();
377 inputStrs.add(lineFromFile);
382 while (i < inputStrs.size()) {
383 instr = inputStrs.get(i);
384 if (instr.contains("Total Prefixes")) {
385 String[] result = instr.split(":");
387 totPfx = result[1].trim();
388 } catch (Exception e) {
396 key.append(BgpConstants.BGP_COUNTER_TOTAL_PFX).append(":").
397 append("Bgp_Total_Prefixes");
398 countersMap.put(key.toString(), totPfx);
402 * The below function parses the output of "show ip bgp vpnv4 all" saved in a file.
403 * Below is the sample output for the same :-
404 * show ip bgp vpnv4 all
406 BGP table version is 0, local router ID is 10.183.181.21
408 Route Distinguisher: 100:1
409 *>i15.15.15.15/32 10.183.181.25 0 100 0 ?
410 *>i17.18.17.17/32 10.183.181.25 0 100 0 ?
411 *>i17.18.17.17/32 10.183.181.25 0 100 0 ?
412 *>i17.18.17.17/32 10.183.181.25 0 100 0 ?
413 Route Distinguisher: 100:2
414 *>i16.16.16.16/32 10.183.181.25 0 100 0 ?
415 *>i18.18.18.18/32 10.183.181.25 0 100 0 ?
416 *>i17.18.17.17/32 10.183.181.25 0 100 0 ?
419 public void parse_ip_bgp_vpnv4_all() {
420 File file = new File("cmd_ip_bgp_vpnv4_all.txt");
423 List<String> inputStrs = new ArrayList<String>();
426 scanner = new Scanner(file);
427 } catch (IOException e) {
428 System.err.println("Could not process the file " + file.getAbsolutePath());
431 while (scanner.hasNextLine()) {
432 lineFromFile = scanner.nextLine();
433 inputStrs.add(lineFromFile);
437 while (i < inputStrs.size()) {
438 instr = inputStrs.get(i);
439 if (instr.contains("Route Distinguisher")) {
440 String[] result = instr.split(":");
441 rd = result[1].trim() + "_" + result[2].trim();
442 i = processRouteCount(rd, i + 1, inputStrs);
450 public int processRouteCount(String rd, int startIndex, List<String> inputStrs) {
451 int num = startIndex, route_count = 0;
453 StringBuilder key = new StringBuilder();
454 str = inputStrs.get(num);
456 while (str != null && !str.trim().equals("") &&
457 num <inputStrs.size()) {
458 if (str.contains("Route Distinguisher")) {
460 key.append(BgpConstants.BGP_COUNTER_RD_ROUTE_COUNT).append(":").
461 append("BGP_RD_").append(rd).append("_route_count");
462 countersMap.put(key.toString(), Integer.toString(route_count));
467 if (num == inputStrs.size()) {
470 str = inputStrs.get(num);
472 if (route_count == 0) {
473 // Erroneous condition, should never happen.
474 // Implies that the file contains marker for RD without routes.
475 // will form an infinite loop if not broken
476 // by sending a big number back.
480 key.append(BgpConstants.BGP_COUNTER_RD_ROUTE_COUNT).append(":").
481 append("BGP_RD_").append(rd).append("_route_count");
482 countersMap.put(key.toString(), Integer.toString(route_count));
486 public void resetCounters() {
488 resetFile("cmd_ip_bgp_summary.txt");
489 resetFile("cmd_bgp_ipv4_unicast_statistics.txt");
490 resetFile("cmd_ip_bgp_vpnv4_all.txt");
493 public void resetFile(String fileName) {
494 File fileHndl = (new File(fileName));
498 success = fileHndl.delete();
501 writer = new PrintWriter(fileHndl);
504 } catch (Exception e) {