Merge "Resolve Bug:707 - ConfigPusher should wait for netconf-impl to register JMX...
[controller.git] / opendaylight / netconf / netconf-impl / src / main / java / org / opendaylight / controller / netconf / impl / osgi / NetconfOperationRouterImpl.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.controller.netconf.impl.osgi;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Maps;
12 import com.google.common.collect.Sets;
13 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
14 import org.opendaylight.controller.netconf.api.NetconfOperationRouter;
15 import org.opendaylight.controller.netconf.api.NetconfSession;
16 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
17 import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
18 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
19 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCommit;
20 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultGetSchema;
21 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStartExi;
22 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStopExi;
23 import org.opendaylight.controller.netconf.mapping.api.DefaultNetconfOperation;
24 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
25 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
26 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
27 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
28 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceSnapshot;
29 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.w3c.dom.Document;
33
34 import java.util.Collections;
35 import java.util.HashSet;
36 import java.util.Map;
37 import java.util.Set;
38 import java.util.TreeMap;
39
40 public class NetconfOperationRouterImpl implements NetconfOperationRouter {
41
42     private static final Logger logger = LoggerFactory.getLogger(NetconfOperationRouterImpl.class);
43
44     private final NetconfOperationServiceSnapshot netconfOperationServiceSnapshot;
45     private Set<NetconfOperation> allNetconfOperations;
46
47     private NetconfOperationRouterImpl(NetconfOperationServiceSnapshot netconfOperationServiceSnapshot) {
48         this.netconfOperationServiceSnapshot = netconfOperationServiceSnapshot;
49     }
50
51     private void initNetconfOperations(Set<NetconfOperation> allOperations) {
52         allNetconfOperations = allOperations;
53     }
54
55     /**
56      * Factory method to produce instance of NetconfOperationRouter
57      */
58     public static NetconfOperationRouter createOperationRouter(NetconfOperationServiceSnapshot netconfOperationServiceSnapshot,
59                                                                CapabilityProvider capabilityProvider, DefaultCommitNotificationProducer commitNotifier) {
60         NetconfOperationRouterImpl router = new NetconfOperationRouterImpl(netconfOperationServiceSnapshot);
61
62         Preconditions.checkNotNull(netconfOperationServiceSnapshot);
63         Preconditions.checkNotNull(capabilityProvider);
64
65         final String sessionId = netconfOperationServiceSnapshot.getNetconfSessionIdForReporting();
66
67         final Set<NetconfOperation> defaultNetconfOperations = Sets.newHashSet();
68         defaultNetconfOperations.add(new DefaultGetSchema(capabilityProvider, sessionId));
69         defaultNetconfOperations.add(new DefaultCloseSession(sessionId, router));
70         defaultNetconfOperations.add(new DefaultStartExi(sessionId));
71         defaultNetconfOperations.add(new DefaultStopExi(sessionId));
72         defaultNetconfOperations.add(new DefaultCommit(commitNotifier, capabilityProvider, sessionId, router));
73
74         router.initNetconfOperations(getAllNetconfOperations(defaultNetconfOperations, netconfOperationServiceSnapshot));
75
76         return router;
77     }
78
79     private static Set<NetconfOperation> getAllNetconfOperations(Set<NetconfOperation> defaultNetconfOperations,
80             NetconfOperationServiceSnapshot netconfOperationServiceSnapshot) {
81         Set<NetconfOperation> result = new HashSet<>();
82         result.addAll(defaultNetconfOperations);
83
84         for (NetconfOperationService netconfOperationService : netconfOperationServiceSnapshot.getServices()) {
85             final Set<NetconfOperation> netOpsFromService = netconfOperationService.getNetconfOperations();
86             for (NetconfOperation netconfOperation : netOpsFromService) {
87                 Preconditions.checkState(result.contains(netconfOperation) == false,
88                         "Netconf operation %s already present", netconfOperation);
89                 result.add(netconfOperation);
90             }
91         }
92         return Collections.unmodifiableSet(result);
93     }
94
95     @Override
96     public synchronized Document onNetconfMessage(Document message,
97             NetconfSession session) throws NetconfDocumentedException {
98         Preconditions.checkNotNull(allNetconfOperations, "Operation router was not initialized properly");
99
100         NetconfOperationExecution netconfOperationExecution;
101         String messageAsString = XmlUtil.toString(message);
102
103         try {
104             netconfOperationExecution = getNetconfOperationWithHighestPriority(message, session);
105         } catch (IllegalArgumentException | IllegalStateException e) {
106             logger.warn("Unable to handle rpc {} on session {}", messageAsString, session, e);
107
108             String errorMessage = String.format("Unable to handle rpc %s on session %s", messageAsString, session);
109             Map<String, String> errorInfo = Maps.newHashMap();
110
111             NetconfDocumentedException.ErrorTag tag;
112             if (e instanceof IllegalArgumentException) {
113                 errorInfo.put(NetconfDocumentedException.ErrorTag.operation_not_supported.toString(), e.getMessage());
114                 tag = NetconfDocumentedException.ErrorTag.operation_not_supported;
115             } else {
116                 errorInfo.put(NetconfDocumentedException.ErrorTag.operation_failed.toString(), e.getMessage());
117                 tag = NetconfDocumentedException.ErrorTag.operation_failed;
118             }
119
120             throw new NetconfDocumentedException(errorMessage, e, NetconfDocumentedException.ErrorType.application,
121                     tag, NetconfDocumentedException.ErrorSeverity.error, errorInfo);
122         } catch (RuntimeException e) {
123             throw handleUnexpectedEx("Unexpected exception during netconf operation sort", e);
124         }
125
126         try {
127             return executeOperationWithHighestPriority(message, netconfOperationExecution, messageAsString);
128         } catch (RuntimeException e) {
129             throw handleUnexpectedEx("Unexpected exception during netconf operation execution", e);
130         }
131     }
132
133     @Override
134     public void close() throws Exception {
135         netconfOperationServiceSnapshot.close();
136     }
137
138     private NetconfDocumentedException handleUnexpectedEx(String s, Exception e) throws NetconfDocumentedException {
139         logger.error(s, e);
140
141         Map<String, String> info = Maps.newHashMap();
142         info.put(NetconfDocumentedException.ErrorSeverity.error.toString(), e.toString());
143         return new NetconfDocumentedException("Unexpected error",
144                 NetconfDocumentedException.ErrorType.application,
145                 NetconfDocumentedException.ErrorTag.operation_failed,
146                 NetconfDocumentedException.ErrorSeverity.error, info);
147     }
148
149     private Document executeOperationWithHighestPriority(Document message,
150             NetconfOperationExecution netconfOperationExecution, String messageAsString)
151             throws NetconfDocumentedException {
152         logger.debug("Forwarding netconf message {} to {}", messageAsString, netconfOperationExecution.netconfOperation);
153         return netconfOperationExecution.execute(message);
154     }
155
156     private NetconfOperationExecution getNetconfOperationWithHighestPriority(
157             Document message, NetconfSession session) {
158
159         TreeMap<HandlingPriority, NetconfOperation> sortedByPriority = getSortedNetconfOperationsWithCanHandle(
160                 message, session);
161
162         Preconditions.checkArgument(sortedByPriority.isEmpty() == false,
163                 "No %s available to handleWithNoSubsequentOperations message %s", NetconfOperation.class.getName(),
164                 XmlUtil.toString(message));
165
166         return NetconfOperationExecution.createExecutionChain(sortedByPriority, sortedByPriority.lastKey());
167     }
168
169     private TreeMap<HandlingPriority, NetconfOperation> getSortedNetconfOperationsWithCanHandle(Document message,
170             NetconfSession session) {
171         TreeMap<HandlingPriority, NetconfOperation> sortedPriority = Maps.newTreeMap();
172
173         for (NetconfOperation netconfOperation : allNetconfOperations) {
174             final HandlingPriority handlingPriority = netconfOperation.canHandle(message);
175             if (netconfOperation instanceof DefaultNetconfOperation) {
176                 ((DefaultNetconfOperation) netconfOperation).setNetconfSession(session);
177             }
178             if (handlingPriority.equals(HandlingPriority.CANNOT_HANDLE) == false) {
179
180                 Preconditions.checkState(sortedPriority.containsKey(handlingPriority) == false,
181                         "Multiple %s available to handle message %s with priority %s",
182                         NetconfOperation.class.getName(), message, handlingPriority);
183                 sortedPriority.put(handlingPriority, netconfOperation);
184             }
185         }
186         return sortedPriority;
187     }
188
189     private static class NetconfOperationExecution implements NetconfOperationChainedExecution {
190         private final NetconfOperation netconfOperation;
191         private NetconfOperationChainedExecution subsequentExecution;
192
193         private NetconfOperationExecution(NetconfOperation netconfOperation, NetconfOperationChainedExecution subsequentExecution) {
194             this.netconfOperation = netconfOperation;
195             this.subsequentExecution = subsequentExecution;
196         }
197
198         @Override
199         public boolean isExecutionTermination() {
200             return false;
201         }
202
203         @Override
204         public Document execute(Document message) throws NetconfDocumentedException {
205             return netconfOperation.handle(message, subsequentExecution);
206         }
207
208         public static NetconfOperationExecution createExecutionChain(
209                 TreeMap<HandlingPriority, NetconfOperation> sortedByPriority, HandlingPriority handlingPriority) {
210             NetconfOperation netconfOperation = sortedByPriority.get(handlingPriority);
211             HandlingPriority subsequentHandlingPriority = sortedByPriority.lowerKey(handlingPriority);
212
213             NetconfOperationChainedExecution subsequentExecution = null;
214
215             if (subsequentHandlingPriority != null) {
216                 subsequentExecution = createExecutionChain(sortedByPriority, subsequentHandlingPriority);
217             } else {
218                 subsequentExecution = EXECUTION_TERMINATION_POINT;
219             }
220
221             return new NetconfOperationExecution(netconfOperation, subsequentExecution);
222         }
223     }
224
225     @Override
226     public String toString() {
227         return "NetconfOperationRouterImpl{" + "netconfOperationServiceSnapshot=" + netconfOperationServiceSnapshot
228                 + '}';
229     }
230 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.