Integrate netconf-mapping-api into netconf-server
[netconf.git] / protocol / netconf-server / src / main / java / org / opendaylight / netconf / server / 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.server;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableMap;
14 import org.opendaylight.netconf.api.DocumentedException;
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.messages.NotificationMessage;
19 import org.opendaylight.netconf.api.monitoring.NetconfMonitoringService;
20 import org.opendaylight.netconf.api.monitoring.SessionEvent;
21 import org.opendaylight.netconf.api.monitoring.SessionListener;
22 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
23 import org.opendaylight.netconf.api.xml.XmlUtil;
24 import org.opendaylight.netconf.server.osgi.NetconfOperationRouterImpl;
25 import org.opendaylight.netconf.server.spi.SubtreeFilter;
26 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
27 import org.opendaylight.yangtools.yang.common.ErrorTag;
28 import org.opendaylight.yangtools.yang.common.ErrorType;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.w3c.dom.Document;
32 import org.w3c.dom.NamedNodeMap;
33 import org.w3c.dom.Node;
34
35 public class NetconfServerSessionListener implements NetconfSessionListener<NetconfServerSession> {
36     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionListener.class);
37
38     private final SessionListener monitoringSessionListener;
39     private final NetconfOperationRouterImpl operationRouter;
40     private final AutoCloseable onSessionDownCloseable;
41
42     NetconfServerSessionListener(final NetconfOperationRouterImpl operationRouter,
43             final NetconfMonitoringService monitoringService, final AutoCloseable onSessionDownCloseable) {
44         this.operationRouter = requireNonNull(operationRouter);
45         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, 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     @Override
112     public void onError(final NetconfServerSession session, final Exception failure) {
113         session.onIncommingRpcFail();
114         monitoringSessionListener.onSessionEvent(SessionEvent.inRpcFail(session));
115         throw new IllegalStateException("Unable to process incoming message", failure);
116     }
117
118     public void onNotification(final NetconfServerSession session, final NotificationMessage notification) {
119         monitoringSessionListener.onSessionEvent(SessionEvent.notification(session));
120     }
121
122     private NetconfMessage processDocument(final NetconfMessage netconfMessage, final NetconfServerSession session)
123             throws DocumentedException {
124
125         final Document incomingDocument = netconfMessage.getDocument();
126         final Node rootNode = incomingDocument.getDocumentElement();
127
128         if (rootNode.getLocalName().equals(XmlNetconfConstants.RPC_KEY)) {
129             final Document responseDocument = XmlUtil.newDocument();
130             checkMessageId(rootNode);
131
132             Document rpcReply = operationRouter.onNetconfMessage(incomingDocument, session);
133
134             rpcReply = SubtreeFilter.applyRpcSubtreeFilter(incomingDocument, rpcReply);
135
136             session.onIncommingRpcSuccess();
137
138             responseDocument.appendChild(responseDocument.importNode(rpcReply.getDocumentElement(), true));
139             return new NetconfMessage(responseDocument);
140         } else {
141             // unknown command, send RFC 4741 p.70 unknown-element
142             /*
143              * Tag: unknown-element Error-type: rpc, protocol, application
144              * Severity: error Error-info: <bad-element> : name of the
145              * unexpected element Description: An unexpected element is present.
146              */
147             throw new DocumentedException("Unknown tag " + rootNode.getNodeName() + " in message:\n" + netconfMessage,
148                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, ErrorSeverity.ERROR,
149                     ImmutableMap.of("bad-element", rootNode.getNodeName()));
150         }
151     }
152
153     private static void checkMessageId(final Node rootNode) throws DocumentedException {
154
155         final NamedNodeMap attributes = rootNode.getAttributes();
156
157         if (attributes.getNamedItemNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
158                 XmlNetconfConstants.MESSAGE_ID) != null) {
159             return;
160         }
161
162         if (attributes.getNamedItem(XmlNetconfConstants.MESSAGE_ID) != null) {
163             return;
164         }
165
166         throw new DocumentedException("Missing attribute " + rootNode.getNodeName(),
167                 ErrorType.RPC, ErrorTag.MISSING_ATTRIBUTE, ErrorSeverity.ERROR, ImmutableMap.of(
168                     "bad-attribute", XmlNetconfConstants.MESSAGE_ID,
169                     "bad-element", XmlNetconfConstants.RPC_KEY));
170     }
171 }