fix ServiceHandler SpotBugs false positives
[transportpce.git] / tests / honeynode / 1.2.1 / netconf-impl / src / main / java / org / opendaylight / netconf / impl / osgi / NetconfSessionMonitoringService.java
1 /*
2  * Copyright (c) 2016 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 package org.opendaylight.netconf.impl.osgi;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Collections2;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.Sets;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.Set;
18 import java.util.concurrent.ScheduledExecutorService;
19 import java.util.concurrent.TimeUnit;
20 import java.util.stream.Collectors;
21 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
22 import org.opendaylight.netconf.api.monitoring.NetconfManagementSession;
23 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
24 import org.opendaylight.netconf.api.monitoring.SessionEvent;
25 import org.opendaylight.netconf.api.monitoring.SessionListener;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Sessions;
27 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SessionsBuilder;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * This class implements {@link SessionListener} to receive updates about Netconf sessions. Instance notifies its
34  * listeners
35  * about session start and end. It also publishes on regular interval list of sessions,
36  * where events like rpc or notification happened.
37  */
38 class NetconfSessionMonitoringService implements SessionListener, AutoCloseable {
39
40     private static final Logger LOG = LoggerFactory.getLogger(NetconfSessionMonitoringService.class);
41
42     private final Set<NetconfManagementSession> sessions = Sets.newHashSet();
43     private final Set<NetconfManagementSession> changedSessions = Sets.newHashSet();
44     private final Set<NetconfMonitoringService.SessionsListener> listeners = Sets.newHashSet();
45     private final ScheduledExecutorService executor;
46     private final long updateInterval;
47     private boolean running;
48
49     /**
50      * Constructor for {@code NetconfSessionMonitoringService}.
51      *
52      * @param schedulingThreadPool thread pool for scheduling session stats updates. If not present, updates won't be
53      *                             scheduled.
54      * @param updateInterval       update interval. If is less than 0, updates won't be scheduled
55      */
56     NetconfSessionMonitoringService(Optional<ScheduledThreadPool> schedulingThreadPool, long updateInterval) {
57         this.updateInterval = updateInterval;
58         if (schedulingThreadPool.isPresent() && updateInterval > 0) {
59             this.executor = schedulingThreadPool.get().getExecutor();
60             LOG.info("/netconf-state/sessions will be updated every {} seconds.", updateInterval);
61         } else {
62             LOG.info("Scheduling thread pool is present = {}, "
63                     + "update interval {}: /netconf-state/sessions won't be updated.",
64                     schedulingThreadPool.isPresent(), updateInterval);
65             this.executor = null;
66         }
67     }
68
69     synchronized Sessions getSessions() {
70         final Collection<Session> managementSessions = Collections2.transform(sessions,
71                 NetconfManagementSession::toManagementSession);
72         return new SessionsBuilder().setSession(ImmutableList.copyOf(managementSessions)).build();
73     }
74
75     @Override
76     public synchronized void onSessionUp(final NetconfManagementSession session) {
77         LOG.debug("Session {} up", session);
78         Preconditions.checkState(!sessions.contains(session), "Session %s was already added", session);
79         sessions.add(session);
80         notifySessionUp(session);
81     }
82
83     @Override
84     public synchronized void onSessionDown(final NetconfManagementSession session) {
85         LOG.debug("Session {} down", session);
86         Preconditions.checkState(sessions.contains(session), "Session %s not present", session);
87         sessions.remove(session);
88         changedSessions.remove(session);
89         notifySessionDown(session);
90     }
91
92     @Override
93     public synchronized void onSessionEvent(SessionEvent event) {
94         changedSessions.add(event.getSession());
95     }
96
97     synchronized AutoCloseable registerListener(final NetconfMonitoringService.SessionsListener listener) {
98         listeners.add(listener);
99         if (!running) {
100             startUpdateSessionStats();
101         }
102         return () -> listeners.remove(listener);
103     }
104
105     @Override
106     public synchronized void close() {
107         stopUpdateSessionStats();
108         listeners.clear();
109         sessions.clear();
110     }
111
112     private synchronized void updateSessionStats() {
113         if (changedSessions.isEmpty()) {
114             return;
115         }
116         final List<Session> changed = changedSessions.stream()
117                 .map(NetconfManagementSession::toManagementSession)
118                 .collect(Collectors.toList());
119         final ImmutableList<Session> sessionImmutableList = ImmutableList.copyOf(changed);
120         for (NetconfMonitoringService.SessionsListener listener : listeners) {
121             listener.onSessionsUpdated(sessionImmutableList);
122         }
123         changedSessions.clear();
124     }
125
126     private void notifySessionUp(NetconfManagementSession managementSession) {
127         Session session = managementSession.toManagementSession();
128         for (NetconfMonitoringService.SessionsListener listener : listeners) {
129             listener.onSessionStarted(session);
130         }
131     }
132
133     private void notifySessionDown(NetconfManagementSession managementSession) {
134         Session session = managementSession.toManagementSession();
135         for (NetconfMonitoringService.SessionsListener listener : listeners) {
136             listener.onSessionEnded(session);
137         }
138     }
139
140     private void startUpdateSessionStats() {
141         if (executor != null) {
142             executor.scheduleAtFixedRate(this::updateSessionStats, 1, updateInterval, TimeUnit.SECONDS);
143             running = true;
144         }
145     }
146
147     private void stopUpdateSessionStats() {
148         if (executor != null) {
149             executor.shutdownNow();
150             running = false;
151         }
152     }
153 }