Merge "Bug 809: Enhancements to the toaster example"
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / NetconfDeviceListener.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 package org.opendaylight.controller.sal.connect.netconf;
9
10 import com.google.common.collect.Sets;
11 import io.netty.util.concurrent.Future;
12 import io.netty.util.concurrent.FutureListener;
13
14 import java.util.ArrayDeque;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.Iterator;
18 import java.util.Queue;
19 import java.util.Set;
20
21 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
22 import org.opendaylight.controller.netconf.api.NetconfMessage;
23 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
24 import org.opendaylight.controller.netconf.client.NetconfClientSession;
25 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
26 import org.opendaylight.controller.netconf.util.xml.XmlElement;
27 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
28 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
29 import org.opendaylight.controller.sal.common.util.Rpcs;
30 import org.opendaylight.controller.sal.core.api.mount.MountProvisionInstance;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.RpcError;
33 import org.opendaylight.yangtools.yang.common.RpcResult;
34 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
35 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
36 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import com.google.common.base.Preconditions;
41 import com.google.common.util.concurrent.Futures;
42 import com.google.common.util.concurrent.ListenableFuture;
43
44 public class NetconfDeviceListener implements NetconfClientSessionListener {
45     private static final class Request {
46         final UncancellableFuture<RpcResult<CompositeNode>> future;
47         final NetconfMessage request;
48         final QName rpc;
49
50         private Request(UncancellableFuture<RpcResult<CompositeNode>> future, NetconfMessage request, final QName rpc) {
51             this.future = future;
52             this.request = request;
53             this.rpc = rpc;
54         }
55     }
56
57     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceListener.class);
58     private final Queue<Request> requests = new ArrayDeque<>();
59     private final NetconfDevice device;
60     private NetconfClientSession session;
61
62     public NetconfDeviceListener(final NetconfDevice device) {
63         this.device = Preconditions.checkNotNull(device);
64     }
65
66     @Override
67     public synchronized void onSessionUp(final NetconfClientSession session) {
68         LOG.debug("Session with {} established as address {} session-id {}",
69                 device.getName(), device.getSocketAddress(), session.getSessionId());
70
71         this.session = session;
72
73         final Set<QName> caps = device.getCapabilities(session.getServerCapabilities());
74         LOG.trace("Server {} advertized capabilities {}", device.getName(), caps);
75
76         // Select the appropriate provider
77         final SchemaSourceProvider<String> delegate;
78         if (NetconfRemoteSchemaSourceProvider.isSupportedFor(caps)) {
79             delegate = new NetconfRemoteSchemaSourceProvider(device);
80             // FIXME caps do not contain urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring, since it is filtered out in getCapabilitites
81         } else if(session.getServerCapabilities().contains(NetconfRemoteSchemaSourceProvider.IETF_NETCONF_MONITORING.getNamespace().toString())) {
82             delegate = new NetconfRemoteSchemaSourceProvider(device);
83         } else {
84             LOG.info("Netconf server {} does not support IETF Netconf Monitoring", device.getName());
85             delegate = SchemaSourceProviders.noopProvider();
86         }
87
88         device.bringUp(delegate, caps, isRollbackSupported(session.getServerCapabilities()));
89
90     }
91
92     private static boolean isRollbackSupported(final Collection<String> serverCapabilities) {
93         // TODO rollback capability cannot be searched for in Set<QName> caps
94         // since this set does not contain module-less capabilities
95         return Sets.newHashSet(serverCapabilities).contains(NetconfMapping.NETCONF_ROLLBACK_ON_ERROR_URI.toString());
96     }
97
98     private synchronized void tearDown(final Exception e) {
99         session = null;
100
101         /*
102          * Walk all requests, check if they have been executing
103          * or cancelled and remove them from the queue.
104          */
105         final Iterator<Request> it = requests.iterator();
106         while (it.hasNext()) {
107             final Request r = it.next();
108             if (r.future.isUncancellable()) {
109                 // FIXME: add a RpcResult instead?
110                 r.future.setException(e);
111                 it.remove();
112             } else if (r.future.isCancelled()) {
113                 // This just does some house-cleaning
114                 it.remove();
115             }
116         }
117
118         device.bringDown();
119     }
120
121     @Override
122     public void onSessionDown(final NetconfClientSession session, final Exception e) {
123         LOG.debug("Session with {} went down", device.getName(), e);
124         tearDown(e);
125     }
126
127     @Override
128     public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
129         LOG.debug("Session with {} terminated {}", session, reason);
130         tearDown(new RuntimeException(reason.getErrorMessage()));
131     }
132
133     @Override
134     public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
135         /*
136          * Dispatch between notifications and messages. Messages need to be processed
137          * with lock held, notifications do not.
138          */
139         if (isNotification(message)) {
140             processNotification(message);
141         } else {
142             processMessage(message);
143         }
144     }
145
146     private synchronized void processMessage(final NetconfMessage message) {
147         final Request r = requests.peek();
148         if (r.future.isUncancellable()) {
149             requests.poll();
150             LOG.debug("Matched {} to {}", r.request, message);
151
152             try {
153                 NetconfMapping.checkValidReply(r.request, message);
154             } catch (IllegalStateException e) {
155                 LOG.warn("Invalid request-reply match, reply message contains different message-id", e);
156                 r.future.setException(e);
157                 return;
158             }
159
160             try {
161                 NetconfMapping.checkSuccessReply(message);
162             } catch (NetconfDocumentedException | IllegalStateException e) {
163                 LOG.warn("Error reply from remote device", e);
164                 r.future.setException(e);
165                 return;
166             }
167
168             r.future.set(NetconfMapping.toRpcResult(message, r.rpc, device.getSchemaContext()));
169         } else {
170             LOG.warn("Ignoring unsolicited message", message);
171         }
172     }
173
174     synchronized ListenableFuture<RpcResult<CompositeNode>> sendRequest(final NetconfMessage message, final QName rpc) {
175         if (session == null) {
176             LOG.debug("Session to {} is disconnected, failing RPC request {}", device.getName(), message);
177             return Futures.<RpcResult<CompositeNode>>immediateFuture(new RpcResult<CompositeNode>() {
178                 @Override
179                 public boolean isSuccessful() {
180                     return false;
181                 }
182
183                 @Override
184                 public CompositeNode getResult() {
185                     return null;
186                 }
187
188                 @Override
189                 public Collection<RpcError> getErrors() {
190                     // FIXME: indicate that the session is down
191                     return Collections.emptySet();
192                 }
193             });
194         }
195
196         final Request req = new Request(new UncancellableFuture<RpcResult<CompositeNode>>(true), message, rpc);
197         requests.add(req);
198
199         session.sendMessage(req.request).addListener(new FutureListener<Void>() {
200             @Override
201             public void operationComplete(final Future<Void> future) throws Exception {
202                 if (!future.isSuccess()) {
203                     // We expect that a session down will occur at this point
204                     LOG.debug("Failed to send request {}", XmlUtil.toString(req.request.getDocument()), future.cause());
205                     req.future.setException(future.cause());
206                 } else {
207                     LOG.trace("Finished sending request {}", req.request);
208                 }
209             }
210         });
211
212         return req.future;
213     }
214
215     /**
216      * Process an incoming notification.
217      *
218      * @param notification Notification message
219      */
220     private void processNotification(final NetconfMessage notification) {
221         this.device.logger.debug("Received NETCONF notification.", notification);
222         CompositeNode domNotification = NetconfMapping.toNotificationNode(notification, device.getSchemaContext());
223         if (domNotification == null) {
224             return;
225         }
226
227         MountProvisionInstance mountInstance =  this.device.getMountInstance();
228         if (mountInstance != null) {
229             mountInstance.publish(domNotification);
230         }
231     }
232
233     private static boolean isNotification(final NetconfMessage message) {
234         final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
235         return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
236     }
237 }