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