BUG-2635 Netconf monitoring for md-sal netconf northbound
[controller.git] / opendaylight / netconf / netconf-impl / src / main / java / org / opendaylight / controller / netconf / impl / osgi / NetconfMonitoringServiceImpl.java
1 /*
2  * Copyright (c) 2013 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.controller.netconf.impl.osgi;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableList.Builder;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.Maps;
18 import com.google.common.collect.Sets;
19 import io.netty.util.internal.ConcurrentSet;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.concurrent.ConcurrentHashMap;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.controller.netconf.api.Capability;
28 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
29 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
30 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfStateBuilder;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Capabilities;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.CapabilitiesBuilder;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SchemasBuilder;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Sessions;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SessionsBuilder;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.SchemaBuilder;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.SchemaKey;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 public class NetconfMonitoringServiceImpl implements NetconfMonitoringService, AutoCloseable {
49
50     private static final Schema.Location NETCONF_LOCATION = new Schema.Location(Schema.Location.Enumeration.NETCONF);
51     private static final List<Schema.Location> NETCONF_LOCATIONS = ImmutableList.of(NETCONF_LOCATION);
52     private static final Logger LOG = LoggerFactory.getLogger(NetconfMonitoringServiceImpl.class);
53     private static final Function<NetconfManagementSession, Session> SESSION_FUNCTION = new Function<NetconfManagementSession, Session>() {
54         @Override
55         public Session apply(@Nonnull final NetconfManagementSession input) {
56             return input.toManagementSession();
57         }
58     };
59     private static final Function<Capability, Uri> CAPABILITY_TO_URI = new Function<Capability, Uri>() {
60         @Override
61         public Uri apply(final Capability input) {
62             return new Uri(input.getCapabilityUri());
63         }
64     };
65
66     private final Set<NetconfManagementSession> sessions = new ConcurrentSet<>();
67     private final NetconfOperationServiceFactory netconfOperationProvider;
68     private final Map<Uri, Capability> capabilities = new ConcurrentHashMap<>();
69
70     private final Set<MonitoringListener> listeners = Sets.newHashSet();
71
72     public NetconfMonitoringServiceImpl(final NetconfOperationServiceFactory netconfOperationProvider) {
73         this.netconfOperationProvider = netconfOperationProvider;
74         netconfOperationProvider.registerCapabilityListener(this);
75     }
76
77     @Override
78     public synchronized void onSessionUp(final NetconfManagementSession session) {
79         LOG.debug("Session {} up", session);
80         Preconditions.checkState(!sessions.contains(session), "Session %s was already added", session);
81         sessions.add(session);
82         notifyListeners();
83     }
84
85     @Override
86     public synchronized void onSessionDown(final NetconfManagementSession session) {
87         LOG.debug("Session {} down", session);
88         Preconditions.checkState(sessions.contains(session), "Session %s not present", session);
89         sessions.remove(session);
90         notifyListeners();
91     }
92
93     @Override
94     public synchronized Sessions getSessions() {
95         return new SessionsBuilder().setSession(ImmutableList.copyOf(Collections2.transform(sessions, SESSION_FUNCTION))).build();
96     }
97
98     @Override
99     public synchronized Schemas getSchemas() {
100         try {
101             return transformSchemas(netconfOperationProvider.getCapabilities());
102         } catch (final RuntimeException e) {
103             throw e;
104         } catch (final Exception e) {
105             throw new IllegalStateException("Exception while closing", e);
106         }
107     }
108
109     @Override
110     public synchronized String getSchemaForCapability(final String moduleName, final Optional<String> revision) {
111
112         // FIXME not effective at all
113
114         Map<String, Map<String, String>> mappedModulesToRevisionToSchema = Maps.newHashMap();
115
116         final Collection<Capability> caps = capabilities.values();
117
118         for (Capability cap : caps) {
119             if (!cap.getModuleName().isPresent()
120                     || !cap.getRevision().isPresent()
121                     || !cap.getCapabilitySchema().isPresent()){
122                 continue;
123             }
124
125             final String currentModuleName = cap.getModuleName().get();
126             Map<String, String> revisionMap = mappedModulesToRevisionToSchema.get(currentModuleName);
127             if (revisionMap == null) {
128                 revisionMap = Maps.newHashMap();
129                 mappedModulesToRevisionToSchema.put(currentModuleName, revisionMap);
130             }
131
132             String currentRevision = cap.getRevision().get();
133             revisionMap.put(currentRevision, cap.getCapabilitySchema().get());
134         }
135
136         Map<String, String> revisionMapRequest = mappedModulesToRevisionToSchema.get(moduleName);
137         Preconditions.checkState(revisionMapRequest != null, "Capability for module %s not present, " + ""
138                 + "available modules : %s", moduleName, Collections2.transform(caps, CAPABILITY_TO_URI));
139
140         if (revision.isPresent()) {
141             String schema = revisionMapRequest.get(revision.get());
142
143             Preconditions.checkState(schema != null,
144                     "Capability for module %s:%s not present, available revisions for module: %s", moduleName,
145                     revision.get(), revisionMapRequest.keySet());
146
147             return schema;
148         } else {
149             Preconditions.checkState(revisionMapRequest.size() == 1,
150                     "Expected 1 capability for module %s, available revisions : %s", moduleName,
151                     revisionMapRequest.keySet());
152             return revisionMapRequest.values().iterator().next();
153         }
154     }
155
156     @Override
157     public synchronized Capabilities getCapabilities() {
158         return new CapabilitiesBuilder().setCapability(Lists.newArrayList(capabilities.keySet())).build();
159     }
160
161     @Override
162     public synchronized AutoCloseable registerListener(final MonitoringListener listener) {
163         listeners.add(listener);
164         listener.onStateChanged(getCurrentNetconfState());
165         return new AutoCloseable() {
166             @Override
167             public void close() throws Exception {
168                 listeners.remove(listener);
169             }
170         };
171     }
172
173     private NetconfState getCurrentNetconfState() {
174         return new NetconfStateBuilder()
175                 .setCapabilities(getCapabilities())
176                 .setSchemas(getSchemas())
177                 .setSessions(getSessions())
178                 .build();
179     }
180
181     private static Schemas transformSchemas(final Set<Capability> caps) {
182         final List<Schema> schemas = new ArrayList<>(caps.size());
183         for (final Capability cap : caps) {
184             if (cap.getCapabilitySchema().isPresent()) {
185                 final SchemaBuilder builder = new SchemaBuilder();
186                 Preconditions.checkState(cap.getModuleNamespace().isPresent());
187                 builder.setNamespace(new Uri(cap.getModuleNamespace().get()));
188
189                 Preconditions.checkState(cap.getRevision().isPresent());
190                 final String version = cap.getRevision().get();
191                 builder.setVersion(version);
192
193                 Preconditions.checkState(cap.getModuleName().isPresent());
194                 final String identifier = cap.getModuleName().get();
195                 builder.setIdentifier(identifier);
196
197                 builder.setFormat(Yang.class);
198
199                 builder.setLocation(transformLocations(cap.getLocation()));
200
201                 builder.setKey(new SchemaKey(Yang.class, identifier, version));
202
203                 schemas.add(builder.build());
204             }
205         }
206
207         return new SchemasBuilder().setSchema(schemas).build();
208     }
209
210     private static List<Schema.Location> transformLocations(final Collection<String> locations) {
211         if (locations.isEmpty()) {
212             return NETCONF_LOCATIONS;
213         }
214
215         final Builder<Schema.Location> b = ImmutableList.builder();
216         b.add(NETCONF_LOCATION);
217
218         for (final String location : locations) {
219             b.add(new Schema.Location(new Uri(location)));
220         }
221
222         return b.build();
223     }
224
225     @Override
226     public synchronized void onCapabilitiesAdded(final Set<Capability> addedCaps) {
227         // FIXME howto check for duplicates
228         this.capabilities.putAll(Maps.uniqueIndex(addedCaps, CAPABILITY_TO_URI));
229         notifyListeners();
230     }
231
232     private void notifyListeners() {
233         for (final MonitoringListener listener : listeners) {
234             listener.onStateChanged(getCurrentNetconfState());
235         }
236     }
237
238     @Override
239     public synchronized void onCapabilitiesRemoved(final Set<Capability> addedCaps) {
240         for (final Capability addedCap : addedCaps) {
241             capabilities.remove(addedCap.getCapabilityUri());
242         }
243         notifyListeners();
244     }
245
246     @Override
247     public synchronized void close() throws Exception {
248         listeners.clear();
249         sessions.clear();
250         capabilities.clear();
251     }
252 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.