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