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