Merge "Clean up netconf-parent root pom"
[netconf.git] / netconf / netconf-impl / src / main / java / org / opendaylight / netconf / impl / NetconfServerSessionListener.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
9 package org.opendaylight.netconf.impl;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import org.opendaylight.controller.config.util.xml.DocumentedException;
14 import org.opendaylight.controller.config.util.xml.XmlUtil;
15 import org.opendaylight.netconf.api.NetconfMessage;
16 import org.opendaylight.netconf.api.NetconfSessionListener;
17 import org.opendaylight.netconf.api.NetconfTerminationReason;
18 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
19 import org.opendaylight.netconf.api.monitoring.SessionEvent;
20 import org.opendaylight.netconf.api.monitoring.SessionListener;
21 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
22 import org.opendaylight.netconf.impl.osgi.NetconfOperationRouter;
23 import org.opendaylight.netconf.notifications.NetconfNotification;
24 import org.opendaylight.netconf.util.messages.SendErrorExceptionUtil;
25 import org.opendaylight.netconf.util.messages.SubtreeFilter;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import org.w3c.dom.Document;
29 import org.w3c.dom.NamedNodeMap;
30 import org.w3c.dom.Node;
31
32 public class NetconfServerSessionListener implements NetconfSessionListener<NetconfServerSession> {
33
34     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionListener.class);
35     private final SessionListener monitoringSessionListener;
36     private final NetconfOperationRouter operationRouter;
37     private final AutoCloseable onSessionDownCloseable;
38
39     public NetconfServerSessionListener(final NetconfOperationRouter operationRouter,
40                                         final NetconfMonitoringService monitoringService,
41                                         final AutoCloseable onSessionDownCloseable) {
42         this.operationRouter = operationRouter;
43         this.monitoringSessionListener = monitoringService.getSessionListener();
44         this.onSessionDownCloseable = onSessionDownCloseable;
45     }
46
47     @Override
48     public void onSessionUp(final NetconfServerSession netconfNetconfServerSession) {
49         monitoringSessionListener.onSessionUp(netconfNetconfServerSession);
50     }
51
52     @Override
53     public void onSessionDown(final NetconfServerSession netconfNetconfServerSession, final Exception cause) {
54         LOG.debug("Session {} down, reason: {}", netconfNetconfServerSession, cause.getMessage());
55         onDown(netconfNetconfServerSession);
56     }
57
58     @SuppressWarnings("checkstyle:IllegalCatch")
59     public void onDown(final NetconfServerSession netconfNetconfServerSession) {
60         monitoringSessionListener.onSessionDown(netconfNetconfServerSession);
61
62         try {
63             operationRouter.close();
64         } catch (final Exception closingEx) {
65             LOG.debug("Ignoring exception while closing operationRouter", closingEx);
66         }
67         try {
68             onSessionDownCloseable.close();
69         } catch (final Exception ex) {
70             LOG.debug("Ignoring exception while closing onSessionDownCloseable", ex);
71         }
72     }
73
74     @Override
75     public void onSessionTerminated(final NetconfServerSession netconfNetconfServerSession,
76                                     final NetconfTerminationReason netconfTerminationReason) {
77         LOG.debug("Session {} terminated, reason: {}", netconfNetconfServerSession,
78                 netconfTerminationReason.getErrorMessage());
79         onDown(netconfNetconfServerSession);
80     }
81
82     @SuppressWarnings("checkstyle:IllegalCatch")
83     @Override
84     public void onMessage(final NetconfServerSession session, final NetconfMessage netconfMessage) {
85         try {
86
87             Preconditions.checkState(operationRouter != null, "Cannot handle message, session up was not yet received");
88             // there is no validation since the document may contain yang schemas
89             final NetconfMessage message = processDocument(netconfMessage,
90                     session);
91             LOG.debug("Responding with message {}", message);
92             session.sendMessage(message);
93             monitoringSessionListener.onSessionEvent(SessionEvent.inRpcSuccess(session));
94         } catch (final RuntimeException e) {
95             // TODO: should send generic error or close session?
96             LOG.error("Unexpected exception", e);
97             session.onIncommingRpcFail();
98             monitoringSessionListener.onSessionEvent(SessionEvent.inRpcFail(session));
99             throw new IllegalStateException("Unable to process incoming message " + netconfMessage, e);
100         } catch (final DocumentedException e) {
101             LOG.trace("Error occurred while processing message", e);
102             session.onOutgoingRpcError();
103             session.onIncommingRpcFail();
104             monitoringSessionListener.onSessionEvent(SessionEvent.inRpcFail(session));
105             monitoringSessionListener.onSessionEvent(SessionEvent.outRpcError(session));
106             SendErrorExceptionUtil.sendErrorMessage(session, e, netconfMessage);
107         }
108     }
109
110     public void onNotification(final NetconfServerSession session, final NetconfNotification notification) {
111         monitoringSessionListener.onSessionEvent(SessionEvent.notification(session));
112     }
113
114     private NetconfMessage processDocument(final NetconfMessage netconfMessage, final NetconfServerSession session)
115             throws DocumentedException {
116
117         final Document incomingDocument = netconfMessage.getDocument();
118         final Node rootNode = incomingDocument.getDocumentElement();
119
120         if (rootNode.getLocalName().equals(XmlNetconfConstants.RPC_KEY)) {
121             final Document responseDocument = XmlUtil.newDocument();
122             checkMessageId(rootNode);
123
124             Document rpcReply = operationRouter.onNetconfMessage(incomingDocument, session);
125
126             rpcReply = SubtreeFilter.applyRpcSubtreeFilter(incomingDocument, rpcReply);
127
128             session.onIncommingRpcSuccess();
129
130             responseDocument.appendChild(responseDocument.importNode(rpcReply.getDocumentElement(), true));
131             return new NetconfMessage(responseDocument);
132         } else {
133             // unknown command, send RFC 4741 p.70 unknown-element
134             /*
135              * Tag: unknown-element Error-type: rpc, protocol, application
136              * Severity: error Error-info: <bad-element> : name of the
137              * unexpected element Description: An unexpected element is present.
138              */
139             throw new DocumentedException("Unknown tag " + rootNode.getNodeName() + " in message:\n" + netconfMessage,
140                     DocumentedException.ErrorType.PROTOCOL, DocumentedException.ErrorTag.UNKNOWN_ELEMENT,
141                     DocumentedException.ErrorSeverity.ERROR, ImmutableMap.of("bad-element",
142                     rootNode.getNodeName()));
143         }
144     }
145
146     private static void checkMessageId(final Node rootNode) throws DocumentedException {
147
148         final NamedNodeMap attributes = rootNode.getAttributes();
149
150         if (attributes.getNamedItemNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
151                 XmlNetconfConstants.MESSAGE_ID) != null) {
152             return;
153         }
154
155         if (attributes.getNamedItem(XmlNetconfConstants.MESSAGE_ID) != null) {
156             return;
157         }
158
159         throw new DocumentedException("Missing attribute " + rootNode.getNodeName(),
160                 DocumentedException.ErrorType.RPC, DocumentedException.ErrorTag.MISSING_ATTRIBUTE,
161                 DocumentedException.ErrorSeverity.ERROR,
162                 ImmutableMap.of("bad-attribute", XmlNetconfConstants.MESSAGE_ID,
163                         "bad-element", XmlNetconfConstants.RPC_KEY));
164     }
165 }