Enhancements in BGP module
[netvirt.git] / bgpmanager / impl / src / main / java / org / opendaylight / netvirt / bgpmanager / oam / BgpCounters.java
1 /*
2  * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netvirt.bgpmanager.oam;
10
11 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12
13 import java.io.BufferedReader;
14 import java.io.BufferedWriter;
15 import java.io.File;
16 import java.io.FileNotFoundException;
17 import java.io.FileWriter;
18 import java.io.IOException;
19 import java.io.InputStreamReader;
20 import java.io.PrintWriter;
21 import java.net.Inet4Address;
22 import java.net.Inet6Address;
23 import java.net.InetAddress;
24 import java.net.Socket;
25 import java.net.SocketTimeoutException;
26 import java.net.UnknownHostException;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Scanner;
31 import java.util.concurrent.ConcurrentHashMap;
32 import javax.inject.Inject;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.infrautils.metrics.Counter;
35 import org.opendaylight.infrautils.metrics.Labeled;
36 import org.opendaylight.infrautils.metrics.MetricDescriptor;
37 import org.opendaylight.infrautils.metrics.MetricProvider;
38 import org.opendaylight.netvirt.bgpmanager.thrift.gen.af_afi;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 @SuppressFBWarnings("DM_DEFAULT_ENCODING")
43 public class BgpCounters implements Runnable, AutoCloseable {
44     public static final String BGP_VPNV6_FILE = "cmd_ip_bgp_vpnv6_all.txt";
45     public static final String BGP_VPNV4_FILE = "cmd_ip_bgp_vpnv4_all.txt";
46     public static final String BGP_EVPN_FILE = "cmd_bgp_l2vpn_evpn_all.txt";
47     public static final String BGP_VPNV6_SUMMARY_FILE = "cmd_ip_bgp_vpnv6_all_summary.txt";
48     public static final String BGP_VPNV4_SUMMARY_FILE = "cmd_ip_bgp_vpnv4_all_summary.txt";
49     public static final String BGP_EVPN_SUMMARY_FILE = "cmd_bgp_evpn_all_summary.txt";
50     public static final String BFD_NBR_DETAIL_FILE = "cmd_bfd_neighbors_details.txt";
51
52
53     // BFD related constants
54     public static final int LINE = 1; // line where the ip address of neigbor present after "NeighbroAddr"
55     public static final int NBR_IP_WORD_INDEX = 1; // word where the ip address is present (count start from 0)
56     public static final int RX_COUNT_WORD_INDEX = 1; // word where the Rx Count is present after split :
57     public static final int TX_COUNT_WORD_INDEX = 1; // word where the Tx Count is present after split :
58
59     private static final Logger LOG = LoggerFactory.getLogger(BgpCounters.class);
60
61     private final Map<String, String> totalPfxMap = new ConcurrentHashMap<>();
62     private final Map<String, String> ipv4PfxMap = new ConcurrentHashMap<>();
63     private final Map<String, String> ipv6PfxMap = new ConcurrentHashMap<>();
64
65     private final String bgpSdncMip;
66     private final MetricProvider metricProvider;
67
68     @Inject
69     public BgpCounters(String mipAddress, final MetricProvider metricProvider) {
70         this.metricProvider = metricProvider;
71         this.bgpSdncMip = mipAddress;
72     }
73
74     @Override
75     public void close() {
76     }
77
78     @Override
79     public void run() {
80         LOG.debug("Fetching counters from BGP");
81         resetCounters();
82         fetchCmdOutputs("cmd_ip_bgp_summary.txt", "show ip bgp summary");
83         fetchCmdOutputs("cmd_bgp_ipv4_unicast_statistics.txt", "show bgp ipv4 unicast statistics");
84         fetchCmdOutputs(BGP_VPNV4_FILE, "show ip bgp vpnv4 all");
85         fetchCmdOutputs(BGP_VPNV6_FILE, "show ip bgp vpnv6 all");
86         fetchCmdOutputs(BGP_EVPN_FILE, "show bgp l2vpn evpn all");
87         fetchCmdOutputs(BFD_NBR_DETAIL_FILE, "show bgp bfd neighbors details");
88
89         parseIpBgpSummary();
90         parseIpBgpVpnv4All();
91         parseIpBgpVpnv6All();
92         parseBgpL2vpnEvpnAll();
93         parseBfdNbrsDetails();
94         LOG.debug("Finished updating the counters from BGP");
95     }
96
97     void fetchCmdOutputs(String filename, String cmdName) {
98         try (Socket socket = new Socket(bgpSdncMip, 2605);
99              PrintWriter toRouter = new PrintWriter(socket.getOutputStream(), true);
100              BufferedReader fromRouter = new BufferedReader(new InputStreamReader(socket.getInputStream()));
101              BufferedWriter toFile = new BufferedWriter(new FileWriter(filename, true))) {
102             socket.setSoTimeout(2 * 1000);
103
104             // Wait for the password prompt
105             StringBuilder sb = new StringBuilder();
106             int read;
107             char[] cbuf = new char[10];
108             while (!sb.toString().contains("Password:")) {
109                 if ((read = fromRouter.read(cbuf)) == -1) {
110                     LOG.error("Connection closed by BGPd.");
111                     return;
112                 }
113                 sb.append(cbuf, 0, read);
114             }
115
116             // Send the password
117             toRouter.println(BgpConstants.QBGP_VTY_PASSWORD);
118
119             // Wait for the prompt (ending with '>' or '#')
120             sb = new StringBuilder();
121             String prompt = null;
122             while (prompt == null) {
123                 switch (read = fromRouter.read()) {
124                     case -1:
125                         LOG.error("Connection closed by BGPd, read {}", sb.toString());
126                         return;
127                     case '>':
128                         // Fall through
129                     case '#':
130                         sb.append((char) read);
131                         prompt = sb.toString().trim();
132                         break;
133                     default:
134                         sb.append((char) read);
135                         break;
136                 }
137
138             }
139
140             toRouter.flush();
141
142             // Wait for '#'
143             while ((read = fromRouter.read()) != '#') {
144                 if (read == -1) {
145                     LOG.error("Connection closed by BGPd, read {}", sb.toString());
146                     return;
147                 }
148             }
149
150
151             // Send the command
152             toRouter.println(cmdName);
153             toRouter.flush();
154
155
156             // Read all the router's output
157             sb = new StringBuilder();
158             cbuf = new char[1024];
159             while ((read = fromRouter.read(cbuf)) != -1) {
160                 sb.append(cbuf, 0, read);
161                 if (sb.toString().trim().endsWith(prompt)) {
162                     break;
163                 }
164             }
165
166             // Only keep output up to the last prompt
167             int lastPromptIndex = sb.lastIndexOf(prompt);
168             if (lastPromptIndex >= 0) {
169                 sb.delete(lastPromptIndex, sb.length());
170             }
171
172             // Store in the file
173             toFile.write(sb.toString().trim());
174             socket.close();
175             toFile.flush();
176             toFile.close();
177             toRouter.flush();
178             toRouter.close();
179             fromRouter.close();
180         } catch (UnknownHostException e) {
181             LOG.info("Unknown host exception occured while socket creation {} ", bgpSdncMip);
182         } catch (SocketTimeoutException e) {
183             LOG.info("Socket timeout Exception occured while socket creation");
184         } catch (IOException e) {
185             LOG.error("I/O error ip {} {}",bgpSdncMip, e.getMessage());
186         }
187     }
188
189     private static boolean validate(@NonNull final String ip, af_afi afi) {
190         if (ip.equals("")) {
191             return false;
192         }
193         int identifiedAFI = 0;
194         try {
195             InetAddress address = InetAddress.getByName(ip);
196             if (address instanceof Inet6Address) {
197                 identifiedAFI = af_afi.AFI_IPV6.getValue();
198             } else if (address instanceof Inet4Address) {
199                 identifiedAFI = af_afi.AFI_IP.getValue();
200             }
201         } catch (java.net.UnknownHostException e) {
202             /*if exception is catched then the prefix is not an IPv6 and IPv4*/
203             LOG.error("Unrecognized ip address ipAddress: {}", ip);
204         }
205         return identifiedAFI == afi.getValue() ? true : false;
206     }
207
208     /*
209      * The below function parses the output of "show ip bgp summary" saved in a file.
210      * Below is the snippet for the same :-
211         <output>
212         BGP router identifier 10.183.254.53, local AS number 101
213         .....
214         Neighbor        V    AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
215         10.183.254.76   4   100       3       4        0    0    0 00:01:27        0
216         .........
217         Total number of neighbors 1
218         </output>
219      */
220
221     private void parseIpBgpSummary() {
222         File file = new File("cmd_ip_bgp_summary.txt");
223
224         try (Scanner scanner = new Scanner(file)) {
225             boolean startEntries = false;
226             while (scanner.hasNextLine()) {
227                 String str = scanner.nextLine();
228                 if (str.contains("State/PfxRcd")) {
229                     startEntries = true;
230                 } else if (startEntries) {
231                     String[] result = str.split("\\s+");
232                     if (result.length < 5) {
233                         return;
234                     }
235                     String strIp = result[0].trim();
236                     if (!validate(strIp, af_afi.AFI_IP)) {
237                         return;
238                     }
239                     final String as = result[2];
240                     final String rx = result[3];
241                     final String tx = result[4];
242
243                     Counter counter = getCounter(BgpConstants.BGP_COUNTER_NBR_PKTS_RX, as,
244                             rx, null, strIp, null, "bgp-peer");
245                     updateCounter(counter, Long.parseLong(rx));
246
247                     counter = getCounter(BgpConstants.BGP_COUNTER_NBR_PKTS_TX, as,
248                             null, tx, strIp, null, "bgp-peer");
249                     updateCounter(counter, Long.parseLong(tx));
250                 }
251             }
252         } catch (IOException e) {
253             LOG.error("Could not process the file {}", file.getAbsolutePath());
254         }
255     }
256
257     /*
258      *  The below function parses the output of "show ip bgp vpnv4 all" saved in a file.
259      *  Below is the sample output for the same :-
260      *  show ip bgp vpnv4 all
261         <output>
262         BGP table version is 0, local router ID is 10.183.181.21
263         ......
264         Route Distinguisher: 100:1
265         *>i15.15.15.15/32   10.183.181.25            0    100      0 ?
266         *>i17.18.17.17/32   10.183.181.25            0    100      0 ?
267         *>i17.18.17.17/32   10.183.181.25            0    100      0 ?
268         *>i17.18.17.17/32   10.183.181.25            0    100      0 ?
269         Route Distinguisher: 100:2
270         *>i16.16.16.16/32   10.183.181.25            0    100      0 ?
271         *>i18.18.18.18/32   10.183.181.25            0    100      0 ?
272         *>i17.18.17.17/32   10.183.181.25            0    100      0 ?
273         </output>
274      */
275     private void parseIpBgpVpnv4All() {
276         File file = new File(BGP_VPNV4_FILE);
277         List<String> inputStrs = new ArrayList<>();
278
279         try (Scanner scanner = new Scanner(file)) {
280             while (scanner.hasNextLine()) {
281                 inputStrs.add(scanner.nextLine());
282             }
283         } catch (IOException e) {
284             LOG.error("Could not process the file {}", file.getAbsolutePath());
285             return;
286         }
287         for (int i = 0; i < inputStrs.size(); i++) {
288             String instr = inputStrs.get(i);
289             if (instr.contains("Route Distinguisher")) {
290                 String[] result = instr.split(":");
291                 String rd = result[1].trim() + "_" + result[2].trim();
292                 i = processRouteCount(rd + "_VPNV4", i + 1, inputStrs);
293             }
294         }
295         long bgpIpv4Pfxs = calculateBgpIpv4Prefixes();
296         LOG.trace("BGP IPV4 Prefixes:{}",bgpIpv4Pfxs);
297         Counter counter = getCounter(BgpConstants.BGP_COUNTER_IPV4_PFX, null, null, null,
298                 null, null, "bgp-peer");
299         updateCounter(counter, bgpIpv4Pfxs);
300     }
301
302     /*
303      *  The below function parses the output of "show ip bgp vpnv6 all" saved in a file.
304      *  Below is the sample output for the same :-
305      *  show ip bgp vpnv6 all
306         <output>
307         BGP table version is 0, local router ID is 10.183.181.21
308         ......
309         Route Distinguisher: 100:1
310         *>i2001:db8:0:2::/128   10.183.181.25            0    100      0 ?
311         *>i2001:db8:0:2::/128   10.183.181.25            0    100      0 ?
312         *>i2001:db8:0:2::/128   10.183.181.25            0    100      0 ?
313         *>i2001:db8:0:2::/128   10.183.181.25            0    100      0 ?
314         Route Distinguisher: 100:2
315         *>i2001:db9:0:3::/128   10.183.181.25            0    100      0 ?
316         *>i2001:db9:0:3::/128   10.183.181.25            0    100      0 ?
317         *>i2001:db9:0:3::/128   10.183.181.25            0    100      0 ?
318         </output>
319      */
320     private void parseIpBgpVpnv6All() {
321         File file = new File(BGP_VPNV6_FILE);
322         List<String> inputStrs = new ArrayList<>();
323
324         try (Scanner scanner = new Scanner(file)) {
325             while (scanner.hasNextLine()) {
326                 inputStrs.add(scanner.nextLine());
327             }
328         } catch (IOException e) {
329             LOG.error("Could not process the file {}", file.getAbsolutePath());
330             return;
331         }
332         for (int i = 0; i < inputStrs.size(); i++) {
333             String instr = inputStrs.get(i);
334             if (instr.contains("Route Distinguisher")) {
335                 String[] result = instr.split(":");
336                 String rd = result[1].trim() + "_" + result[2].trim();
337                 i = processRouteCount(rd + "_VPNV6", i + 1, inputStrs);
338             }
339         }
340         long bgpIpv6Pfxs = calculateBgpIpv6Prefixes();
341         LOG.trace("BGP IPV6 Prefixes:{}",bgpIpv6Pfxs);
342         Counter counter = getCounter(BgpConstants.BGP_COUNTER_IPV6_PFX, null, null, null,
343                 null, null, "bgp-peer");
344         updateCounter(counter, bgpIpv6Pfxs);
345     }
346
347     private void parseBgpL2vpnEvpnAll() {
348         File file = new File(BGP_EVPN_FILE);
349         List<String> inputStrs = new ArrayList<>();
350
351         try (Scanner scanner = new Scanner(file)) {
352             while (scanner.hasNextLine()) {
353                 inputStrs.add(scanner.nextLine());
354             }
355         } catch (IOException e) {
356             LOG.error("Could not process the file {}", file.getAbsolutePath());
357             return;
358         }
359         for (int i = 0; i < inputStrs.size(); i++) {
360             String instr = inputStrs.get(i);
361             if (instr.contains("Route Distinguisher")) {
362                 String[] result = instr.split(":");
363                 String rd = result[1].trim() + "_" + result[2].trim();
364                 i = processRouteCount(rd + "_EVPN", i + 1, inputStrs);
365                 LOG.trace("BGP Total Prefixes:{}", i);
366             }
367         }
368         /*populate the "BgpTotalPrefixes" counter by combining
369         the prefixes that are calculated per RD basis*/
370         long bgpTotalPfxs = calculateBgpTotalPrefixes();
371         LOG.trace("BGP Total Prefixes:{}",bgpTotalPfxs);
372         Counter counter = getCounter(BgpConstants.BGP_COUNTER_TOTAL_PFX, null, null, null,
373                 null, null, "bgp-peer");
374         updateCounter(counter, bgpTotalPfxs);
375     }
376
377     private void parseBfdNbrsDetails() {
378         File file = new File(BFD_NBR_DETAIL_FILE);
379         List<String> inputStrs = new ArrayList<>();
380
381         try (Scanner scanner = new Scanner(file)) {
382             while (scanner.hasNextLine()) {
383                 inputStrs.add(scanner.nextLine());
384             }
385         } catch (IOException e) {
386             LOG.error("Could not process the file {}", file.getAbsolutePath());
387             return;
388         }
389         String neighborIPstr = null;
390         for (int i = 0; i < inputStrs.size(); i++) {
391             String instr = inputStrs.get(i);
392             if (instr.contains("NeighAddr") && instr.contains("State")) {
393                 neighborIPstr = inputStrs.get(i + LINE).split("\\s+")[NBR_IP_WORD_INDEX];
394                 if (!validate(neighborIPstr, af_afi.AFI_IP)) {
395                     LOG.error("Invalid neighbor IP {}", neighborIPstr);
396                     return;
397                 }
398             }
399             if ((neighborIPstr != null) && inputStrs.get(i).contains("Rx Count:")
400                     && inputStrs.get(i + 1).contains("Tx Count:")) {
401                 //Rx Count:
402                 long rxCount = 0;
403                 try {
404                     rxCount = Long.parseLong(inputStrs.get(i).split(":")[RX_COUNT_WORD_INDEX].trim());
405                 }
406                 catch (NumberFormatException e) {
407                     LOG.error("Rx count Number format exception: {}",
408                         inputStrs.get(i + 1).split(":")[RX_COUNT_WORD_INDEX].trim());
409                     rxCount = 0;
410                 }
411
412                 //Tx Count:
413                 long txCount = 0;
414                 try {
415                     txCount = Long.parseLong(inputStrs.get(i + 1).split(":")
416                                   [TX_COUNT_WORD_INDEX].trim());
417                 } catch (NumberFormatException e) {
418                     LOG.error("Tx count Number format exception: {}",
419                         inputStrs.get(i + 1).split(":")[TX_COUNT_WORD_INDEX].trim());
420                     txCount = 0;
421                 }
422                 Counter counter = getCounter(BgpConstants.BFD_COUNTER_NBR_PKTS_RX, null,
423                         Long.toString(rxCount), null, neighborIPstr, null, "bfd-peer");
424                 updateCounter(counter, rxCount);
425
426                 counter = getCounter(BgpConstants.BFD_COUNTER_NBR_PKTS_TX, null,
427                         null, Long.toString(txCount), neighborIPstr, null, "bfd-peer");
428                 updateCounter(counter, txCount);
429
430                 //Counter fetching is done, search for next BFD Neighbor IP
431                 neighborIPstr = null;
432             }
433         }
434     }
435
436     private int processRouteCount(String rd, int startIndex, List<String> inputStrs) {
437         int num = startIndex;
438         long routeCount = 0;
439
440         String bgpRdRouteCountKey = BgpConstants.BGP_COUNTER_RD_ROUTE_COUNT + rd;
441         Counter counter = getCounter(BgpConstants.BGP_COUNTER_RD_ROUTE_COUNT, null, null, null,
442                 null, rd, "bgp-peer");
443         for (String str = inputStrs.get(num); str != null && !str.trim().equals("")
444                 && num < inputStrs.size();
445                 str = inputStrs.get(num)) {
446             if (str.contains("Route Distinguisher")) {
447                 totalPfxMap.put(bgpRdRouteCountKey, Long.toString(routeCount));
448                 updateCounter(counter, routeCount);
449                 return num - 1;
450             }
451             else if (rd.contains("VPNV4")) {
452                 ipv4PfxMap.put(bgpRdRouteCountKey, Long.toString(++routeCount));
453                 updateCounter(counter, routeCount);
454             } else if (rd.contains("VPNV6")) {
455                 ipv6PfxMap.put(bgpRdRouteCountKey, Long.toString(++routeCount));
456                 updateCounter(counter, routeCount);
457             }
458             num++;
459             if (num == inputStrs.size()) {
460                 break;
461             }
462         }
463         if (routeCount == 0) {
464             // Erroneous condition, should never happen.
465             // Implies that the file contains marker for RD  without routes.
466             // will form an infinite loop if not broken
467             // by sending a big number back.
468             return Integer.MAX_VALUE;
469         }
470         updateCounter(counter, routeCount);
471         return num - 1;
472     }
473
474     private Long calculateBgpIpv4Prefixes() {
475         return ipv4PfxMap.entrySet().stream()
476                 .map(Map.Entry::getValue).mapToLong(Long::parseLong).sum();
477     }
478
479     private Long calculateBgpIpv6Prefixes() {
480         return ipv6PfxMap.entrySet().stream()
481                 .map(Map.Entry::getValue).mapToLong(Long::parseLong).sum();
482     }
483
484     private Long calculateBgpTotalPrefixes() {
485         return totalPfxMap.entrySet().stream()
486                 .map(Map.Entry::getValue).mapToLong(Long::parseLong).sum();
487     }
488
489     private void resetCounters() {
490         totalPfxMap.clear();
491         ipv6PfxMap.clear();
492         ipv4PfxMap.clear();
493         resetFile("cmd_ip_bgp_summary.txt");
494         resetFile("cmd_bgp_ipv4_unicast_statistics.txt");
495         resetFile(BGP_VPNV4_FILE);
496         resetFile(BGP_VPNV6_FILE);
497         resetFile(BGP_EVPN_FILE);
498         resetFile(BFD_NBR_DETAIL_FILE);
499     }
500
501     static void resetFile(String fileName) {
502         File file = new File(fileName);
503         if (!file.delete()) {
504             try (PrintWriter pw = new PrintWriter(file)) {
505                 pw.print("");
506             } catch (FileNotFoundException e) {
507                 // Ignored
508             }
509         }
510     }
511
512     static Map<String, String> parseIpBgpVpnAllSummary(Map<String, String> countMap,
513                                                        String cmdFile,
514                                                        af_afi afi) {
515         File file = new File(cmdFile);
516
517         try (Scanner scanner = new Scanner(file)) {
518             boolean startEntries = false;
519             while (scanner.hasNextLine()) {
520                 String str = scanner.nextLine();
521                 LOG.trace("str is:: {}", str);
522                 if (str.contains("State/PfxRcd")) {
523                     startEntries = true;
524                 } else if (startEntries) {
525                     String[] result = str.split("\\s+");
526                     if (result.length > 9) {
527                         String strIp = result[0].trim();
528                         LOG.trace("strIp {} ", strIp);
529
530                         if (!validate(strIp, afi)) {
531                             break;
532                         }
533                         String statePfxRcvd = result[9];
534                         countMap.put(strIp, statePfxRcvd);
535                     }
536                 }
537             }
538         } catch (IOException e) {
539             LOG.trace("Could not process the file {}", file.getAbsolutePath());
540             return null;
541         }
542
543         return countMap;
544     }
545
546     static Map<String, String> parseIpBgpVpnv4AllSummary(Map<String, String> countMap) {
547         return BgpCounters.parseIpBgpVpnAllSummary(countMap,
548                                                    BGP_VPNV4_SUMMARY_FILE,
549                                                    af_afi.AFI_IP);
550     }
551
552     static Map<String, String> parseIpBgpVpnv6AllSummary(Map<String, String> countMap) {
553         return BgpCounters.parseIpBgpVpnAllSummary(countMap,
554                                                    BGP_VPNV6_SUMMARY_FILE,
555                                                    af_afi.AFI_IP);
556     }
557
558     static Map<String, String> parseBgpL2vpnEvpnAllSummary(Map<String, String> countMap) {
559         return BgpCounters.parseIpBgpVpnAllSummary(countMap,
560                                                    BGP_EVPN_SUMMARY_FILE,
561                                                    af_afi.AFI_IP);
562     }
563
564     /**
565      * This method updates Counter values.
566      * @param counter object of the Counter
567      * @param counterValue value of Counter
568      */
569     private void updateCounter(Counter counter, long counterValue) {
570         try {
571             /*Reset counter to zero*/
572             counter.decrement(counter.get());
573             /*Set counter to specified value*/
574             counter.increment(counterValue);
575         } catch (IllegalStateException e) {
576             LOG.error("Exception occured during updating the Counter {}", counter, e);
577         }
578     }
579
580     /**
581      * Returns the counter.
582      * This method returns counter and also creates counter if does not exist.
583      *
584      * @param counterName name of the counter.
585      * @param asValue as value.
586      * @param rxValue rx value.
587      * @param txValue tx value.
588      * @param neighborIp neighbor Ipaddress.
589      * @param rdValue rd value.
590      * @return counter object.
591      */
592     private Counter getCounter(String counterName, String asValue,
593             String rxValue, String txValue, String neighborIp, String rdValue, String peerType) {
594         String counterTypeEntityCounter = "entitycounter";
595         String labelKeyEntityType = "entitytype";
596
597         String labelValEntityTypeBgpPeer = null;
598         String labelKeyAsId = "asid";
599         String labelKeyNeighborIp = "neighborip";
600
601         String labelValEntityTypeBgpRd = "bgp-rd";
602         String labelKeyRd = "rd";
603
604         String counterTypeAggregateCounter = "aggregatecounter";
605         String labelKeyCounterName = "name";
606
607         Counter counter = null;
608
609         if (peerType.equals("bgp-peer")) {
610             labelValEntityTypeBgpPeer = "bgp-peer";
611         } else if (peerType.equals("bfd-peer")) {
612             labelValEntityTypeBgpPeer = "bfd-peer";
613         } else {
614             //nothing defined, default to "bgp-peer"
615             labelValEntityTypeBgpPeer = "bgp-peer";
616         }
617
618         if (rxValue != null) {
619             /*
620              * Following is the key pattern for Counter BgpNeighborPacketsReceived
621              * netvirt.bgpmanager.entitycounter{entitytype=bgp-peer, asid=value, neighborip=value, name=countername}
622              * */
623             Labeled<Labeled<Labeled<Labeled<Counter>>>> labeledCounter =
624                     metricProvider.newCounter(MetricDescriptor.builder().anchor(this).project("netvirt")
625                         .module("bgpmanager").id(counterTypeEntityCounter).build(),
626                         labelKeyEntityType, labelKeyAsId,
627                         labelKeyNeighborIp, labelKeyCounterName);
628             counter = labeledCounter.label(labelValEntityTypeBgpPeer).label(asValue)
629                     .label(neighborIp).label(counterName);
630         } else if (txValue != null) {
631             /*
632              * Following is the key pattern for Counter BgpNeighborPacketsSent
633              * netvirt.bgpmanager.entitycounter{entitytype=bgp-peer, asid=value, neighborip=value, name=countername}
634              * */
635             Labeled<Labeled<Labeled<Labeled<Counter>>>> labeledCounter =
636                     metricProvider.newCounter(MetricDescriptor.builder().anchor(this).project("netvirt")
637                         .module("bgpmanager").id(counterTypeEntityCounter).build(),
638                         labelKeyEntityType, labelKeyAsId,
639                         labelKeyNeighborIp, labelKeyCounterName);
640             counter = labeledCounter.label(labelValEntityTypeBgpPeer).label(asValue)
641                     .label(neighborIp).label(counterName);
642         } else if (rdValue != null) {
643             /*
644              * Following is the key pattern for Counter BgpRdRouteCount
645              * netvirt.bgpmanager.entitycounter{entitytype=bgp-rd, rd=value, name=countername}
646              * */
647             Labeled<Labeled<Labeled<Counter>>> labeledCounter =
648                     metricProvider.newCounter(MetricDescriptor.builder().anchor(this).project("netvirt")
649                         .module("bgpmanager").id(counterTypeEntityCounter).build(),
650                         labelKeyEntityType, labelKeyRd,
651                         labelKeyCounterName);
652             counter = labeledCounter.label(labelValEntityTypeBgpRd).label(rdValue)
653                     .label(counterName);
654         } else {
655             /*
656              * Following is the key pattern for Counter BgpTotalPrefixes:Bgp_Total_Prefixes
657              * netvirt.bgpmanager.aggregatecounter{name=countername}
658              * */
659             Labeled<Counter> labeledCounter =
660                     metricProvider.newCounter(MetricDescriptor.builder().anchor(this).project("netvirt")
661                         .module("bgpmanager").id(counterTypeAggregateCounter).build(),
662                         labelKeyCounterName);
663             counter = labeledCounter.label(counterName);
664         }
665         return counter;
666     }
667
668     public void clearBfdNbrCounters(String neighborIPstr) {
669         Counter bfdRxCounter = getCounter(BgpConstants.BFD_COUNTER_NBR_PKTS_RX, null,
670                 Long.toString(0), null, neighborIPstr, null, "bfd-peer");
671         updateCounter(bfdRxCounter, 0);
672
673         Counter bfdTxCounter = getCounter(BgpConstants.BFD_COUNTER_NBR_PKTS_TX, null,
674                     null, Long.toString(0), neighborIPstr, null, "bfd-peer");
675         updateCounter(bfdTxCounter, 0);
676     }
677
678 }