Calculate replicated log data size on recovery
[controller.git] / opendaylight / netconf / mdsal-netconf-connector / src / test / java / org / opendaylight / controller / netconf / mdsal / connector / ops / RuntimeRpcTest.java
1 /*
2  * Copyright (c) 2015 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.mdsal.connector.ops;
10
11 import static org.junit.Assert.assertTrue;
12 import static org.junit.Assert.fail;
13 import static org.mockito.Matchers.any;
14 import static org.mockito.Mockito.doAnswer;
15 import static org.mockito.Mockito.doNothing;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.MockitoAnnotations.initMocks;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.io.ByteSource;
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.Futures;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.net.URI;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.List;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import org.custommonkey.xmlunit.DetailedDiff;
34 import org.custommonkey.xmlunit.Diff;
35 import org.custommonkey.xmlunit.XMLUnit;
36 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.mockito.Mock;
40 import org.mockito.invocation.InvocationOnMock;
41 import org.mockito.stubbing.Answer;
42 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
44 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
46 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
47 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
48 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
49 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
50 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
51 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
52 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
53 import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
54 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
55 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
56 import org.opendaylight.controller.sal.core.api.model.SchemaService;
57 import org.opendaylight.yangtools.concepts.ListenerRegistration;
58 import org.opendaylight.yangtools.yang.common.RpcError;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
64 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.Module;
66 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
69 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
70 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
71 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
72 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.w3c.dom.Document;
76
77 public class RuntimeRpcTest {
78
79     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
80
81     private String sessionIdForReporting = "netconf-test-session1";
82
83     private static Document RPC_REPLY_OK = null;
84
85     static {
86         try {
87             RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
88         } catch (Exception e) {
89             LOG.debug("unable to load rpc reply ok.", e);
90             RPC_REPLY_OK = XmlUtil.newDocument();
91         }
92     }
93
94     private DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
95         @Nonnull
96         @Override
97         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
98             return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
99         }
100
101         @Nonnull
102         @Override
103         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
104             return null;
105         }
106     };
107
108     private DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
109         @Nonnull
110         @Override
111         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
112             return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
113             });
114         }
115
116         @Nonnull
117         @Override
118         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
119             return null;
120         }
121     };
122
123     private DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
124         @Nonnull
125         @Override
126         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
127             Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
128             Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
129             RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(), type.getLastComponent().getLocalName());
130             ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
131             ContainerNode node = ImmutableContainerNodeBuilder.create()
132                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
133                     .withValue(children).build();
134
135             return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(node));
136         }
137
138         @Nonnull
139         @Override
140         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
141             return null;
142         }
143     };
144
145     private SchemaContext schemaContext = null;
146     private CurrentSchemaContext currentSchemaContext = null;
147     @Mock
148     private SchemaService schemaService;
149     @Mock
150     private SchemaContextListener listener;
151     @Mock
152     private ListenerRegistration registration;
153
154     @Before
155     public void setUp() throws Exception {
156
157         initMocks(this);
158         doNothing().when(registration).close();
159         doReturn(listener).when(registration).getInstance();
160         doNothing().when(schemaService).addModule(any(Module.class));
161         doNothing().when(schemaService).removeModule(any(Module.class));
162         doReturn(schemaContext).when(schemaService).getGlobalContext();
163         doReturn(schemaContext).when(schemaService).getSessionContext();
164         doAnswer(new Answer() {
165             @Override
166             public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
167                 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
168                 return registration;
169             }
170         }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
171
172         XMLUnit.setIgnoreWhitespace(true);
173         XMLUnit.setIgnoreAttributeOrder(true);
174
175         this.schemaContext = parseSchemas(getYangSchemas());
176         this.currentSchemaContext = new CurrentSchemaContext(schemaService);
177     }
178
179     @Test
180     public void testVoidOutputRpc() throws Exception {
181         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
182
183         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
184         HandlingPriority priority = rpc.canHandle(rpcDocument);
185         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
186
187         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
188
189         verifyResponse(response, RPC_REPLY_OK);
190     }
191
192     @Test
193     public void testSuccesfullNonVoidInvocation() throws Exception {
194         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
195
196         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
197         HandlingPriority priority = rpc.canHandle(rpcDocument);
198         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
199
200         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
201         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
202     }
203
204     @Test
205     public void testFailedInvocation() throws Exception {
206         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
207
208         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
209         HandlingPriority priority = rpc.canHandle(rpcDocument);
210         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
211
212         try {
213             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
214             fail("should have failed with rpc invocation not implemented yet");
215         } catch (NetconfDocumentedException e) {
216             assertTrue(e.getErrorType() == ErrorType.application);
217             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
218             assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
219         }
220     }
221
222     @Test
223     public void testVoidInputOutputRpc() throws Exception {
224         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
225
226         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
227         HandlingPriority priority = rpc.canHandle(rpcDocument);
228         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
229
230         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
231
232         verifyResponse(response, RPC_REPLY_OK);
233     }
234
235     private void verifyResponse(Document response, Document template) {
236         DetailedDiff dd = new DetailedDiff(new Diff(response, template));
237         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
238         assertTrue(dd.similar());
239     }
240
241     private RpcDefinition getRpcDefinitionFromModule(Module module, URI namespaceURI, String name) {
242         for (RpcDefinition rpcDef : module.getRpcs()) {
243             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
244                     && rpcDef.getQName().getLocalName().equals(name)) {
245                 return rpcDef;
246             }
247         }
248
249         return null;
250
251     }
252
253     private Collection<InputStream> getYangSchemas() {
254         final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
255         final List<InputStream> schemas = new ArrayList<>();
256
257         for (String schemaPath : schemaPaths) {
258             InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
259             schemas.add(resourceAsStream);
260         }
261
262         return schemas;
263     }
264
265     private SchemaContext parseSchemas(Collection<InputStream> schemas) throws IOException, YangSyntaxErrorException {
266         final YangParserImpl parser = new YangParserImpl();
267         Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(schemas);
268         return parser.parseSources(sources);
269     }
270 }