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