Bug 3864: Notify netconf monitoring about changes in session
[netconf.git] / netconf / 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 listeners
34  * about session start and end. It also publishes on regular interval list of sessions,
35  * where events like rpc or notification happened.
36  */
37 class NetconfSessionMonitoringService implements SessionListener, AutoCloseable {
38
39     private static final Logger LOG = LoggerFactory.getLogger(NetconfSessionMonitoringService.class);
40
41     private final Set<NetconfManagementSession> sessions = Sets.newHashSet();
42     private final Set<NetconfManagementSession> changedSessions = Sets.newHashSet();
43     private final Set<NetconfMonitoringService.SessionsListener> listeners = Sets.newHashSet();
44     private final ScheduledExecutorService executor;
45     private final long updateInterval;
46     private boolean running;
47
48     /**
49      * @param schedulingThreadPool thread pool for scheduling session stats updates. If not present, updates won't be scheduled.
50      * @param updateInterval update interval. If is less than 0, updates won't be scheduled
51      */
52     NetconfSessionMonitoringService(Optional<ScheduledThreadPool> schedulingThreadPool, long updateInterval) {
53         this.updateInterval = updateInterval;
54         if (schedulingThreadPool.isPresent() && updateInterval > 0) {
55             this.executor =  schedulingThreadPool.get().getExecutor();
56             LOG.info("/netconf-state/sessions will be updated every {} seconds.", updateInterval);
57         } else {
58             LOG.info("Scheduling thread pool is present = {}, update interval {}: /netconf-state/sessions won't be updated.",
59                     schedulingThreadPool.isPresent(), updateInterval);
60             this.executor = null;
61         }
62     }
63
64     synchronized Sessions getSessions() {
65         final Collection<Session> managementSessions = Collections2.transform(sessions, NetconfManagementSession::toManagementSession);
66         return new SessionsBuilder().setSession(ImmutableList.copyOf(managementSessions)).build();
67     }
68
69     @Override
70     public synchronized void onSessionUp(final NetconfManagementSession session) {
71         LOG.debug("Session {} up", session);
72         Preconditions.checkState(!sessions.contains(session), "Session %s was already added", session);
73         sessions.add(session);
74         notifySessionUp(session);
75     }
76
77     @Override
78     public synchronized void onSessionDown(final NetconfManagementSession session) {
79         LOG.debug("Session {} down", session);
80         Preconditions.checkState(sessions.contains(session), "Session %s not present", session);
81         sessions.remove(session);
82         changedSessions.remove(session);
83         notifySessionDown(session);
84     }
85
86     @Override
87     public synchronized void onSessionEvent(SessionEvent event) {
88         changedSessions.add(event.getSession());
89     }
90
91     synchronized AutoCloseable registerListener(final NetconfMonitoringService.SessionsListener listener) {
92         listeners.add(listener);
93         if (!running) {
94             startUpdateSessionStats();
95         }
96         return new AutoCloseable() {
97             @Override
98             public void close() throws Exception {
99                 listeners.remove(listener);
100             }
101         };
102     }
103
104     @Override
105     public synchronized void close() throws Exception {
106         stopUpdateSessionStats();
107         listeners.clear();
108         sessions.clear();
109     }
110
111     private synchronized void updateSessionStats() {
112         if (changedSessions.isEmpty()) {
113             return;
114         }
115         final List<Session> changed = changedSessions.stream()
116                 .map(NetconfManagementSession::toManagementSession)
117                 .collect(Collectors.toList());
118         final ImmutableList<Session> sessionImmutableList = ImmutableList.copyOf(changed);
119         for (NetconfMonitoringService.SessionsListener listener : listeners) {
120             listener.onSessionsUpdated(sessionImmutableList);
121         }
122         changedSessions.clear();
123     }
124
125     private void notifySessionUp(NetconfManagementSession managementSession) {
126         Session session = managementSession.toManagementSession();
127         for (NetconfMonitoringService.SessionsListener listener : listeners) {
128             listener.onSessionStarted(session);
129         }
130     }
131
132     private void notifySessionDown(NetconfManagementSession managementSession) {
133         Session session = managementSession.toManagementSession();
134         for (NetconfMonitoringService.SessionsListener listener : listeners) {
135             listener.onSessionEnded(session);
136         }
137     }
138
139     private void startUpdateSessionStats() {
140         if (executor != null) {
141             executor.scheduleAtFixedRate(this::updateSessionStats, 1, updateInterval, TimeUnit.SECONDS);
142             running = true;
143         }
144     }
145
146     private void stopUpdateSessionStats() {
147         if (executor != null) {
148             executor.shutdownNow();
149             running = false;
150         }
151     }
152 }