Merge "Added transactions statistics for BI Broker."
[controller.git] / opendaylight / netconf / netconf-impl / src / main / java / org / opendaylight / controller / 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.controller.netconf.impl;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
14 import org.opendaylight.controller.netconf.api.NetconfMessage;
15 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
16 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouterImpl;
17 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
18 import org.opendaylight.controller.netconf.util.messages.SendErrorExceptionUtil;
19 import org.opendaylight.controller.netconf.util.xml.XmlElement;
20 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
21 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
22 import org.opendaylight.protocol.framework.SessionListener;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import org.w3c.dom.Document;
26 import org.w3c.dom.Node;
27
28 import static com.google.common.base.Preconditions.checkState;
29
30 public class NetconfServerSessionListener implements
31         SessionListener<NetconfMessage, NetconfServerSession, NetconfTerminationReason> {
32
33     static final Logger logger = LoggerFactory.getLogger(NetconfServerSessionListener.class);
34     public static final String MESSAGE_ID = "message-id";
35     private final SessionMonitoringService monitoringService;
36
37     private NetconfOperationRouterImpl operationRouter;
38
39     public NetconfServerSessionListener(NetconfOperationRouterImpl operationRouter,
40                                         SessionMonitoringService monitoringService) {
41         this.operationRouter = operationRouter;
42         this.monitoringService = monitoringService;
43     }
44
45     @Override
46     public void onSessionUp(NetconfServerSession netconfNetconfServerSession) {
47         monitoringService.onSessionUp(netconfNetconfServerSession);
48     }
49
50     @Override
51     public void onSessionDown(NetconfServerSession netconfNetconfServerSession, Exception e) {
52         logger.debug("Session {} down, reason: {}", netconfNetconfServerSession, e.getMessage());
53         monitoringService.onSessionDown(netconfNetconfServerSession);
54
55         operationRouter.close();
56     }
57
58     @Override
59     public void onSessionTerminated(NetconfServerSession netconfNetconfServerSession,
60             NetconfTerminationReason netconfTerminationReason) {
61         logger.debug("Session {} terminated, reason: {}", netconfNetconfServerSession,
62                 netconfTerminationReason.getErrorMessage());
63         monitoringService.onSessionDown(netconfNetconfServerSession);
64
65         operationRouter.close();
66     }
67
68     @Override
69     public void onMessage(NetconfServerSession session, NetconfMessage netconfMessage) {
70         try {
71
72             Preconditions.checkState(operationRouter != null, "Cannot handle message, session up was not yet received");
73             // FIXME: there is no validation since the document may contain yang
74             // schemas
75             final NetconfMessage message = processDocument(netconfMessage,
76                     session);
77             logger.debug("Responding with message {}", XmlUtil.toString(message.getDocument()));
78             session.sendMessage(message);
79
80             if (isCloseSession(netconfMessage)) {
81                 closeNetconfSession(session);
82             }
83
84         } catch (final RuntimeException e) {
85             // TODO: should send generic error or close session?
86             logger.error("Unexpected exception", e);
87             session.onIncommingRpcFail();
88             throw new RuntimeException("Unable to process incoming message " + netconfMessage, e);
89         } catch (NetconfDocumentedException e) {
90             session.onOutgoingRpcError();
91             session.onIncommingRpcFail();
92             SendErrorExceptionUtil.sendErrorMessage(session, e, netconfMessage);
93         }
94     }
95
96     private void closeNetconfSession(NetconfServerSession session) {
97         // destroy NetconfOperationService
98         session.close();
99         logger.info("Session {} closed successfully", session.getSessionId());
100     }
101
102     private NetconfMessage processDocument(final NetconfMessage netconfMessage,
103             NetconfServerSession session) throws NetconfDocumentedException {
104
105         final Document incommingDocument = netconfMessage.getDocument();
106         final Node rootNode = incommingDocument.getDocumentElement();
107
108         if (rootNode.getLocalName().equals(XmlNetconfConstants.RPC_KEY)) {
109             final String messageId = rootNode.getAttributes().getNamedItem(MESSAGE_ID).getTextContent();
110             checkState(messageId != null);
111             final Document responseDocument = XmlUtil.newDocument();
112             Document rpcReply = operationRouter.onNetconfMessage(
113                     incommingDocument, session);
114
115             session.onIncommingRpcSuccess();
116
117             responseDocument.appendChild(responseDocument.importNode(rpcReply.getDocumentElement(), true));
118             return new NetconfMessage(responseDocument);
119         } else {
120             // unknown command, send RFC 4741 p.70 unknown-element
121             /*
122              * Tag: unknown-element Error-type: rpc, protocol, application
123              * Severity: error Error-info: <bad-element> : name of the
124              * unexpected element Description: An unexpected element is present.
125              */
126             // TODO add message to error info
127             throw new NetconfDocumentedException("Unknown tag " + rootNode.getNodeName(),
128                     NetconfDocumentedException.ErrorType.protocol, NetconfDocumentedException.ErrorTag.unknown_element,
129                     NetconfDocumentedException.ErrorSeverity.error, ImmutableMap.of("bad-element",
130                             rootNode.getNodeName()));
131         }
132     }
133
134     private static boolean isCloseSession(final NetconfMessage incommingDocument) {
135         final Document document = incommingDocument.getDocument();
136         XmlElement rpcElement = XmlElement.fromDomDocument(document);
137         if (rpcElement.getOnlyChildElementOptionally("close-session").isPresent())
138             return true;
139
140         return false;
141     }
142 }