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