Bug 564 - add missing sal-remote dependency.
[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 java.util.Collections;
11 import java.util.HashSet;
12 import java.util.Map;
13 import java.util.Set;
14 import java.util.TreeMap;
15
16 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
17 import org.opendaylight.controller.netconf.api.NetconfOperationRouter;
18 import org.opendaylight.controller.netconf.api.NetconfSession;
19 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
20 import org.opendaylight.controller.netconf.impl.mapping.CapabilityProvider;
21 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
22 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCommit;
23 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultGetSchema;
24 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStartExi;
25 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStopExi;
26 import org.opendaylight.controller.netconf.mapping.api.DefaultNetconfOperation;
27 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
28 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
29 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
30 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
31 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.w3c.dom.Document;
35
36 import com.google.common.base.Preconditions;
37 import com.google.common.collect.Maps;
38 import com.google.common.collect.Sets;
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 = null;
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 if (e instanceof IllegalStateException) {
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() {
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     public static final NetconfOperationChainedExecution EXECUTION_TERMINATION_POINT = new NetconfOperationChainedExecution() {
190         @Override
191         public boolean isExecutionTermination() {
192             return true;
193         }
194
195         @Override
196         public Document execute(Document requestMessage) throws NetconfDocumentedException {
197             throw new IllegalStateException("This execution represents the termination point in operation execution and cannot be executed itself");
198         }
199     };
200
201     private static class NetconfOperationExecution implements NetconfOperationChainedExecution {
202         private final NetconfOperation netconfOperation;
203         private NetconfOperationChainedExecution subsequentExecution;
204
205         private NetconfOperationExecution(NetconfOperation netconfOperation, NetconfOperationChainedExecution subsequentExecution) {
206             this.netconfOperation = netconfOperation;
207             this.subsequentExecution = subsequentExecution;
208         }
209
210         @Override
211         public boolean isExecutionTermination() {
212             return false;
213         }
214
215         @Override
216         public Document execute(Document message) throws NetconfDocumentedException {
217             return netconfOperation.handle(message, subsequentExecution);
218         }
219
220         public static NetconfOperationExecution createExecutionChain(
221                 TreeMap<HandlingPriority, NetconfOperation> sortedByPriority, HandlingPriority handlingPriority) {
222             NetconfOperation netconfOperation = sortedByPriority.get(handlingPriority);
223             HandlingPriority subsequentHandlingPriority = sortedByPriority.lowerKey(handlingPriority);
224
225             NetconfOperationChainedExecution subsequentExecution = null;
226
227             if (subsequentHandlingPriority != null) {
228                 subsequentExecution = createExecutionChain(sortedByPriority, subsequentHandlingPriority);
229             } else {
230                 subsequentExecution = EXECUTION_TERMINATION_POINT;
231             }
232
233             return new NetconfOperationExecution(netconfOperation, subsequentExecution);
234         }
235     }
236
237     @Override
238     public String toString() {
239         return "NetconfOperationRouterImpl{" + "netconfOperationServiceSnapshot=" + netconfOperationServiceSnapshot
240                 + '}';
241     }
242 }