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