Remove unnecesary imports
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / stats / peer / BGPSessionStatsImpl.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. 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.protocol.bgp.rib.impl.stats.peer;
10
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.Optional;
14 import com.google.common.base.Stopwatch;
15 import io.netty.channel.Channel;
16 import java.net.InetSocketAddress;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
20 import java.util.concurrent.TimeUnit;
21 import java.util.stream.Collectors;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.controller.config.api.IdentityAttributeRef;
24 import org.opendaylight.controller.config.yang.bgp.rib.impl.AdvertisedAddPathTableTypes;
25 import org.opendaylight.controller.config.yang.bgp.rib.impl.AdvertizedTableTypes;
26 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
27 import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorMsgs;
28 import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorReceived;
29 import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorReceivedTotal;
30 import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorSent;
31 import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorSentTotal;
32 import org.opendaylight.controller.config.yang.bgp.rib.impl.KeepAliveMsgs;
33 import org.opendaylight.controller.config.yang.bgp.rib.impl.LocalPeerPreferences;
34 import org.opendaylight.controller.config.yang.bgp.rib.impl.MessagesStats;
35 import org.opendaylight.controller.config.yang.bgp.rib.impl.Received;
36 import org.opendaylight.controller.config.yang.bgp.rib.impl.RemotePeerPreferences;
37 import org.opendaylight.controller.config.yang.bgp.rib.impl.RouteRefreshMsgs;
38 import org.opendaylight.controller.config.yang.bgp.rib.impl.Sent;
39 import org.opendaylight.controller.config.yang.bgp.rib.impl.TotalMsgs;
40 import org.opendaylight.controller.config.yang.bgp.rib.impl.UpdateMsgs;
41 import org.opendaylight.protocol.bgp.rib.impl.BGPSessionImpl;
42 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
43 import org.opendaylight.protocol.util.StatisticsUtil;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Timestamp;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.ZeroBasedCounter32;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParameters;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefresh;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapability;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId;
62 import org.opendaylight.yangtools.yang.binding.Notification;
63 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
64 import org.opendaylight.yangtools.yang.common.QName;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 public final class BGPSessionStatsImpl implements BGPSessionStats {
69     private static final Logger LOG = LoggerFactory.getLogger(BGPSessionStatsImpl.class);
70
71     private final Stopwatch sessionStopwatch;
72     private final BgpSessionState stats;
73     private final BGPSessionImpl session;
74     private final TotalMsgs totalMsgs = new TotalMsgs();
75     private final KeepAliveMsgs kaMsgs = new KeepAliveMsgs();
76     private final UpdateMsgs updMsgs = new UpdateMsgs();
77     private final RouteRefreshMsgs rrMsgs = new RouteRefreshMsgs();
78     private final ErrorMsgs errMsgs = new ErrorMsgs();
79     private final ErrorSentTotal errMsgsSentTotal = new ErrorSentTotal();
80     private final ErrorReceivedTotal errMsgsRecvTotal = new ErrorReceivedTotal();
81     private static final ZeroBasedCounter32 INITIAL_COUNTER = new ZeroBasedCounter32(0L);
82
83     public BGPSessionStatsImpl(@Nonnull final BGPSessionImpl session, @Nonnull final Open remoteOpen, final int holdTimerValue, final int keepAlive, @Nonnull final Channel channel,
84         @Nonnull final Optional<BGPSessionPreferences> localPreferences, @Nonnull final Collection<BgpTableType> tableTypes, @Nonnull final List<AddressFamilies> addPathTypes) {
85         this.session = session;
86         this.sessionStopwatch = Stopwatch.createUnstarted();
87         this.stats = new BgpSessionState();
88         this.stats.setHoldtimeCurrent(holdTimerValue);
89         this.stats.setKeepaliveCurrent(keepAlive);
90         this.stats.setLocalPeerPreferences(setLocalPeerPref(remoteOpen, channel, tableTypes, addPathTypes));
91         this.stats.setRemotePeerPreferences(setRemotePeerPref(channel, localPreferences));
92         this.errMsgs.setErrorReceivedTotal(this.errMsgsRecvTotal);
93         this.errMsgs.setErrorSentTotal(this.errMsgsSentTotal);
94         this.errMsgs.setErrorReceived(new ArrayList<>());
95         this.errMsgs.setErrorSent(new ArrayList<>());
96         initMsgs();
97     }
98
99     private static Received newReceivedInstance() {
100         final Received recv = new Received();
101         recv.setCount(INITIAL_COUNTER);
102         return recv;
103     }
104
105     private static Sent newSentInstance() {
106         final Sent sent = new Sent();
107         sent.setCount(INITIAL_COUNTER);
108         return sent;
109     }
110
111     private static void updateReceivedMsg(final Received received) {
112         requireNonNull(received);
113         final long count = received.getCount() == null ? 0L : received.getCount().getValue();
114         received.setCount(new ZeroBasedCounter32(count + 1));
115         received.setTimestamp(new Timestamp(StatisticsUtil.getCurrentTimestampInSeconds()));
116     }
117
118     private static void updateSentMsg(final Sent sent) {
119         requireNonNull(sent);
120         final long count = sent.getCount() == null ? 0L : sent.getCount().getValue();
121         sent.setCount(new ZeroBasedCounter32(count + 1));
122         sent.setTimestamp(new Timestamp(StatisticsUtil.getCurrentTimestampInSeconds()));
123     }
124
125     private static AdvertizedTableTypes addTableType(final BgpTableType type) {
126         requireNonNull(type);
127         final AdvertizedTableTypes att = new AdvertizedTableTypes();
128         final QName afi = BindingReflections.findQName(type.getAfi()).intern();
129         final QName safi = BindingReflections.findQName(type.getSafi()).intern();
130         att.setAfi(new IdentityAttributeRef(afi.toString()));
131         att.setSafi(new IdentityAttributeRef(safi.toString()));
132         return att;
133     }
134
135     private static AdvertisedAddPathTableTypes addAddPathTableType(final AddressFamilies addressFamilies) {
136         requireNonNull(addressFamilies);
137         final AdvertisedAddPathTableTypes att = new AdvertisedAddPathTableTypes();
138         att.setAfi(new IdentityAttributeRef(BindingReflections.findQName(addressFamilies.getAfi()).intern().toString()));
139         att.setSafi(new IdentityAttributeRef(BindingReflections.findQName(addressFamilies.getSafi()).intern().toString()));
140         att.setSendReceive(addressFamilies.getSendReceive());
141         return att;
142     }
143
144     private static RemotePeerPreferences setRemotePeerPref(final Channel channel, final Optional<BGPSessionPreferences> localPreferences) {
145         requireNonNull(channel);
146         final RemotePeerPreferences pref = new RemotePeerPreferences();
147         final InetSocketAddress isa = (InetSocketAddress) channel.localAddress();
148         pref.setHost(IpAddressBuilder.getDefaultInstance(isa.getAddress().getHostAddress()));
149         pref.setPort(new PortNumber(isa.getPort()));
150         final List<AdvertizedTableTypes> tt = new ArrayList<>();
151         final List<AdvertisedAddPathTableTypes> attList = new ArrayList<>();
152         if (localPreferences.isPresent()) {
153             final BGPSessionPreferences localPref = localPreferences.get();
154             pref.setBgpId(localPref.getBgpId());
155             pref.setAs(localPref.getMyAs());
156             pref.setHoldtimer(localPref.getHoldTime());
157             if (localPref.getParams() != null) {
158                 for (final BgpParameters param : localPref.getParams()) {
159                     for (final OptionalCapabilities capa : param.getOptionalCapabilities()) {
160                         final CParameters cParam = capa.getCParameters();
161                         final CParameters1 capabilities = cParam.getAugmentation(CParameters1.class);
162                         if (capabilities != null) {
163                             final MultiprotocolCapability mc = capabilities.getMultiprotocolCapability();
164                             if (mc != null) {
165                                 final AdvertizedTableTypes att = new AdvertizedTableTypes();
166                                 att.setAfi(new IdentityAttributeRef(BindingReflections.findQName(mc.getAfi()).intern().toString()));
167                                 att.setSafi(new IdentityAttributeRef(BindingReflections.findQName(mc.getSafi()).intern().toString()));
168                                 tt.add(att);
169                             }
170                             if (capabilities.getGracefulRestartCapability() != null) {
171                                 pref.setGrCapability(true);
172                             }
173                             if (capabilities.getAddPathCapability() != null) {
174                                 // FIXME: add path capability is deprecated, replaced by addPathTableTypes
175                                 pref.setAddPathCapability(true);
176
177                                 final List<AdvertisedAddPathTableTypes> addPathTableTypeList = capabilities.getAddPathCapability()
178                                     .getAddressFamilies()
179                                     .stream()
180                                     .map(BGPSessionStatsImpl::addAddPathTableType)
181                                     .collect(Collectors.toList());
182                                 attList.addAll(addPathTableTypeList);
183                             }
184                             if (capabilities.getRouteRefreshCapability() != null) {
185                                 pref.setRouteRefreshCapability(true);
186                             }
187                         }
188                         if (cParam.getAs4BytesCapability() != null) {
189                             pref.setFourOctetAsCapability(true);
190                         }
191                         if (cParam.getBgpExtendedMessageCapability() != null) {
192                             pref.setBgpExtendedMessageCapability(true);
193                         }
194                     }
195                 }
196             }
197         }
198         pref.setAdvertizedTableTypes(tt);
199         pref.setAdvertisedAddPathTableTypes(attList);
200         return pref;
201     }
202
203     private static LocalPeerPreferences setLocalPeerPref(final Open remoteOpen, final Channel channel, final Collection<BgpTableType> tableTypes,
204         final List<AddressFamilies> addPathTypes) {
205         requireNonNull(remoteOpen);
206         requireNonNull(channel);
207         final LocalPeerPreferences pref = new LocalPeerPreferences();
208         final InetSocketAddress isa = (InetSocketAddress) channel.remoteAddress();
209         pref.setHost(IpAddressBuilder.getDefaultInstance(isa.getAddress().getHostAddress()));
210         pref.setPort(new PortNumber(isa.getPort()));
211         pref.setBgpId(new BgpId(remoteOpen.getBgpIdentifier()));
212         pref.setAs(new AsNumber(remoteOpen.getMyAsNumber().longValue()));
213         pref.setHoldtimer(remoteOpen.getHoldTimer());
214
215         final List<AdvertizedTableTypes> tt = tableTypes.stream().map(BGPSessionStatsImpl::addTableType).collect(Collectors.toList());
216         final List<AdvertisedAddPathTableTypes> addPathTableTypeList = addPathTypes.stream().map(BGPSessionStatsImpl::addAddPathTableType)
217             .collect(Collectors.toList());
218
219         if (remoteOpen.getBgpParameters() != null) {
220             for (final BgpParameters param : remoteOpen.getBgpParameters()) {
221                 for (final OptionalCapabilities capa : param.getOptionalCapabilities()) {
222                     final CParameters cParam = capa.getCParameters();
223                     final CParameters1 capabilities = cParam.getAugmentation(CParameters1.class);
224                     if (cParam.getAs4BytesCapability() != null) {
225                         pref.setFourOctetAsCapability(true);
226                     }
227                     if (capabilities != null) {
228                         if (capabilities.getGracefulRestartCapability() != null) {
229                             pref.setGrCapability(true);
230                         }
231                         // FIXME: add-path-capability is deprecated in Boron
232                         if (capabilities.getAddPathCapability() != null) {
233                             pref.setAddPathCapability(true);
234                         }
235                         if (capabilities.getRouteRefreshCapability() != null) {
236                             pref.setRouteRefreshCapability(true);
237                         }
238                     }
239                     if (cParam.getBgpExtendedMessageCapability() != null) {
240                         pref.setBgpExtendedMessageCapability(true);
241                     }
242                 }
243
244             }
245         }
246         pref.setAdvertizedTableTypes(tt);
247         pref.setAdvertisedAddPathTableTypes(addPathTableTypeList);
248         return pref;
249     }
250
251     private void initMsgs() {
252         this.totalMsgs.setReceived(newReceivedInstance());
253         this.totalMsgs.setSent(newSentInstance());
254         this.kaMsgs.setReceived(newReceivedInstance());
255         this.kaMsgs.setSent(newSentInstance());
256         this.updMsgs.setReceived(newReceivedInstance());
257         this.updMsgs.setSent(newSentInstance());
258         this.rrMsgs.setReceived(newReceivedInstance());
259         this.rrMsgs.setSent(newSentInstance());
260         this.errMsgsSentTotal.setCount(INITIAL_COUNTER);
261         this.errMsgsRecvTotal.setCount(INITIAL_COUNTER);
262         this.errMsgs.getErrorSent().clear();
263         this.errMsgs.getErrorReceived().clear();
264     }
265
266     public void startSessionStopwatch() {
267         this.sessionStopwatch.start();
268     }
269
270     private void updateSentMsgTotal() {
271         updateSentMsg(this.totalMsgs.getSent());
272     }
273
274     private void updateReceivedMsgTotal() {
275         updateReceivedMsg(this.totalMsgs.getReceived());
276     }
277
278     private void updateReceivedMsgKA() {
279         updateReceivedMsg(this.kaMsgs.getReceived());
280     }
281
282     public void updateSentMsgKA() {
283         updateSentMsg(this.kaMsgs.getSent());
284     }
285
286     private void updateSentMsgUpd() {
287         updateSentMsg(this.updMsgs.getSent());
288     }
289
290     private void updateReceivedMsgUpd() {
291         updateReceivedMsg(this.updMsgs.getReceived());
292     }
293
294     private void updateSentMsgRR() {
295         updateSentMsg(this.rrMsgs.getSent());
296     }
297
298     private void updateReceivedMsgRR() {
299         updateReceivedMsg(this.rrMsgs.getReceived());
300     }
301
302     private void updateReceivedMsgErr(@Nonnull final Notify error) {
303         requireNonNull(error);
304         final List<ErrorReceived> errList = this.errMsgs.getErrorReceived();
305         ErrorReceived received = null;
306         for (ErrorReceived err : errList) {
307             if (err.getErrorCode().equals(error.getErrorCode()) && err.getErrorSubcode().equals(error.getErrorSubcode())) {
308                 received = err;
309                 break;
310             }
311         }
312         if (null == received) {
313             received = new ErrorReceived();
314             received.setErrorCode(error.getErrorCode());
315             received.setErrorSubcode(error.getErrorSubcode());
316             received.setCount(INITIAL_COUNTER);
317             errList.add(received);
318         }
319         received.setCount(new ZeroBasedCounter32(received.getCount().getValue() + 1));
320         final Timestamp curTimestamp = new Timestamp(StatisticsUtil.getCurrentTimestampInSeconds());
321         received.setTimestamp(curTimestamp);
322         this.errMsgsRecvTotal.setCount(new ZeroBasedCounter32(this.errMsgsRecvTotal.getCount().getValue() + 1));
323         this.errMsgsRecvTotal.setTimestamp(curTimestamp);
324     }
325
326     private void updateSentMsgErr(@Nonnull final Notify error) {
327         requireNonNull(error);
328         final List<ErrorSent> errList = this.errMsgs.getErrorSent();
329         ErrorSent sent = null;
330         for (ErrorSent err : errList) {
331             if (err.getErrorCode().equals(error.getErrorCode()) && err.getErrorSubcode().equals(error.getErrorSubcode())) {
332                 sent = err;
333                 break;
334             }
335         }
336         if (null == sent) {
337             sent = new ErrorSent();
338             sent.setErrorCode(error.getErrorCode());
339             sent.setErrorSubcode(error.getErrorSubcode());
340             sent.setCount(INITIAL_COUNTER);
341             errList.add(sent);
342         }
343         sent.setCount(new ZeroBasedCounter32(sent.getCount().getValue() + 1));
344         final Timestamp curTimestamp = new Timestamp(StatisticsUtil.getCurrentTimestampInSeconds());
345         sent.setTimestamp(curTimestamp);
346         this.errMsgsSentTotal.setCount(new ZeroBasedCounter32(this.errMsgsSentTotal.getCount().getValue() + 1));
347         this.errMsgsSentTotal.setTimestamp(curTimestamp);
348     }
349
350     @Override
351     public BgpSessionState getBgpSessionState() {
352         final MessagesStats msgs = new MessagesStats();
353         msgs.setTotalMsgs(this.totalMsgs);
354         msgs.setErrorMsgs(this.errMsgs);
355         msgs.setKeepAliveMsgs(this.kaMsgs);
356         msgs.setUpdateMsgs(this.updMsgs);
357         msgs.setRouteRefreshMsgs(this.rrMsgs);
358         this.stats.setSessionDuration(StatisticsUtil.formatElapsedTime(this.sessionStopwatch.elapsed(TimeUnit.SECONDS)));
359         this.stats.setSessionState(this.session.getState().toString());
360         this.stats.setMessagesStats(msgs);
361         return this.stats;
362     }
363
364     @Override
365     public void resetBgpSessionStats() {
366         initMsgs();
367     }
368
369     public void updateReceivedMsg(Notification msg) {
370         LOG.trace("Updating received BGP session message count..");
371         this.updateReceivedMsgTotal();
372         if (msg instanceof Notify) {
373             this.updateReceivedMsgErr((Notify) msg);
374         } else if (msg instanceof Keepalive) {
375             this.updateReceivedMsgKA();
376         } else if (msg instanceof RouteRefresh) {
377             this.updateReceivedMsgRR();
378         } else if (msg instanceof Update) {
379             this.updateReceivedMsgUpd();
380         }
381     }
382
383     public void updateSentMsg(Notification msg) {
384         LOG.trace("Updating sent BGP session message count..");
385         this.updateSentMsgTotal();
386         if (msg instanceof Update) {
387             this.updateSentMsgUpd();
388         } else if (msg instanceof Notify) {
389             this.updateSentMsgErr((Notify) msg);
390         } else if (msg instanceof RouteRefresh) {
391             this.updateSentMsgRR();
392         }
393     }
394 }