<feature name='odl-netconf-mdsal' version='${project.version}' description="OpenDaylight :: Netconf :: Mdsal">
<feature version='${config.version}'>odl-config-all</feature>
<feature version='${netconf.version}'>odl-netconf-all</feature>
+ <feature version='${config.version}'>odl-config-netty</feature>
+ <bundle>mvn:org.opendaylight.controller/netconf-tcp/${netconf.version}</bundle>
<bundle>mvn:org.opendaylight.controller/netconf-ssh/${netconf.version}</bundle>
<feature version='${mdsal.version}'>odl-mdsal-broker</feature>
<bundle>mvn:org.opendaylight.controller/mdsal-netconf-connector/${netconf.version}</bundle>
<feature version='${aaa.version}'>odl-aaa-netconf-plugin</feature>
<bundle>mvn:org.opendaylight.controller/netconf-ssh/${netconf.version}</bundle>
</feature>
- <feature name='odl-netconf-tcp' version='${netconf.version}' description="OpenDaylight :: Netconf Connector :: TCP">
+ <feature name='odl-netconf-tcp' version='${netconf.version}' description="OpenDaylight :: Netconf Connector :: TCP">
<feature version='${netconf.version}'>odl-netconf-impl</feature>
+ <feature version='${config.version}'>odl-config-netty</feature>
<bundle>mvn:org.opendaylight.controller/netconf-tcp/${netconf.version}</bundle>
- </feature>
+ </feature>
<feature name='odl-message-bus' version='${project.version}'>
<feature version='${project.version}'>odl-netconf-connector</feature>
<properties>
- <akka.version>2.3.9</akka.version>
+ <akka.version>2.3.10</akka.version>
<appauth.version>0.5.0-SNAPSHOT</appauth.version>
<archetype-app-northbound>0.1.0-SNAPSHOT</archetype-app-northbound>
<arphandler.version>0.6.0-SNAPSHOT</arphandler.version>
.child(TopologyTypes.class)
.augmentation(TopologyTypes1.class);
- private final Map<DataChangeListener, ListenerRegistration<DataChangeListener>> topicListenerRegistrations =
+ private final Map<EventSourceTopic, ListenerRegistration<DataChangeListener>> topicListenerRegistrations =
new ConcurrentHashMap<>();
private final Map<NodeKey, RoutedRpcRegistration<EventSourceService>> routedRpcRegistrations =
- new ConcurrentHashMap<>();;
+ new ConcurrentHashMap<>();
private final DataBroker dataBroker;
private final RpcRegistration<EventAggregatorService> aggregatorRpcReg;
}
public void register(final EventSource eventSource){
- NodeKey nodeKey = eventSource.getSourceNodeKey();
+ NodeKey nodeKey = eventSource.getSourceNodeKey();
final KeyedInstanceIdentifier<Node, NodeKey> sourcePath = EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class, nodeKey);
RoutedRpcRegistration<EventSourceService> reg = rpcRegistry.addRoutedRpcImplementation(EventSourceService.class, eventSource);
reg.registerPath(NodeContext.class, sourcePath);
routedRpcRegistrations.put(nodeKey,reg);
insert(sourcePath);
+
+ for(EventSourceTopic est : topicListenerRegistrations.keySet()){
+ est.notifyNode(EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class, nodeKey));
+ }
}
public void unRegister(final EventSource eventSource){
<configuration>
<instructions>
<Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
- <Export-package>org.opendaylight.controller.sal.binding.spi.*,</Export-package>
+ <Export-Package>
+ org.opendaylight.controller.sal.binding.spi.*,
+ org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.binding.impl.rev131028.*,
+ org.opendaylight.controller.config.yang.md.sal.binding.impl
+ </Export-Package>
<Private-Package>
- org.opendaylight.controller.config.yang.md.sal.binding.impl,
org.opendaylight.controller.sal.binding.impl,
org.opendaylight.controller.sal.binding.impl.*,
org.opendaylight.controller.sal.binding.codegen,
org.opendaylight.controller.md.sal.binding.compat,
org.opendaylight.controller.md.sal.binding.spi,
<!--org.opendaylight.controller.sal.binding.dom.*,-->
- org.opendaylight.controller.sal.binding.osgi.*,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.binding.impl.rev131028.*
+ org.opendaylight.controller.sal.binding.osgi.*
</Private-Package>
</instructions>
</configuration>
private Set<YangInstanceIdentifier> toYangInstanceIdentifiers(final Set<InstanceIdentifier<?>> identifiers) {
final Set<YangInstanceIdentifier> ret = new HashSet<>();
for(final InstanceIdentifier<?> binding: identifiers) {
- ret.add(codec.toNormalized(binding));
+ ret.add(codec.toYangInstanceIdentifierCached(binding));
}
return ret;
}
*/
package org.opendaylight.controller.md.sal.binding.impl;
-import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ClassToInstanceMap;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.lang.reflect.Method;
import java.util.Set;
import org.opendaylight.controller.md.sal.binding.impl.BindingDOMAdapterBuilder.Factory;
-import org.opendaylight.controller.md.sal.binding.impl.RpcServiceAdapter.InvocationDelegate;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.controller.md.sal.dom.api.DOMService;
import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
-import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.RpcService;
import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-public class BindingDOMRpcServiceAdapter implements RpcConsumerRegistry, InvocationDelegate {
+public class BindingDOMRpcServiceAdapter implements RpcConsumerRegistry {
protected static final Factory<RpcConsumerRegistry> BUILDER_FACTORY = new Factory<RpcConsumerRegistry>() {
return proxy;
}
- @Override
- public ListenableFuture<RpcResult<?>> invoke(final SchemaPath rpc, final DataObject input) {
- final CheckedFuture<DOMRpcResult, DOMRpcException> domFuture = domService.invokeRpc(rpc, serialize(rpc,input));
- return transformFuture(rpc,domFuture,codec.getCodecRegistry());
- }
-
private RpcServiceAdapter createProxy(final Class<? extends RpcService> key) {
Preconditions.checkArgument(BindingReflections.isBindingClass(key));
Preconditions.checkArgument(key.isInterface(), "Supplied RPC service type must be interface.");
- final ImmutableMap<Method, SchemaPath> rpcNames = codec.getRpcMethodToSchemaPath(key);
- return new RpcServiceAdapter(key, rpcNames, this);
- }
-
- private NormalizedNode<?, ?> serialize(final SchemaPath rpc,final DataObject input) {
- if(input == null) {
- return null;
- }
- final QName rpcInputIdentifier = QName.create(rpc.getLastComponent(),"input");
- return new LazySerializedContainerNode(rpcInputIdentifier, input, codec.getCodecRegistry());
- }
-
- private static ListenableFuture<RpcResult<?>> transformFuture(final SchemaPath rpc,final ListenableFuture<DOMRpcResult> domFuture, final BindingNormalizedNodeCodecRegistry codec) {
- return Futures.transform(domFuture, new Function<DOMRpcResult, RpcResult<?>>() {
- @Override
- public RpcResult<?> apply(final DOMRpcResult input) {
- if(input instanceof LazySerializedDOMRpcResult) {
- return ((LazySerializedDOMRpcResult) input).bidningRpcResult();
- }
- final NormalizedNode<?, ?> domData = input.getResult();
- final DataObject bindingResult;
- if(domData != null) {
- final SchemaPath rpcOutput = rpc.createChild(QName.create(rpc.getLastComponent(),"output"));
- bindingResult = codec.fromNormalizedNodeRpcData(rpcOutput, (ContainerNode) domData);
- } else {
- bindingResult = null;
- }
- return RpcResult.class.cast(RpcResultBuilder.success(bindingResult).build());
- }
- });
+ return new RpcServiceAdapter(key, codec, domService);
}
private static final class Builder extends BindingDOMAdapterBuilder<RpcConsumerRegistry> {
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableBiMap;
import java.lang.reflect.Method;
import java.util.AbstractMap.SimpleEntry;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-public class BindingToNormalizedNodeCodec implements BindingCodecTreeFactory, BindingNormalizedNodeSerializer, SchemaContextListener, AutoCloseable {
+public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFactory, BindingNormalizedNodeSerializer, SchemaContextListener, AutoCloseable {
private final BindingNormalizedNodeCodecRegistry codecRegistry;
private DataNormalizer legacyToNormalized;
private final GeneratedClassLoadingStrategy classLoadingStrategy;
private BindingRuntimeContext runtimeContext;
+ private final LoadingCache<InstanceIdentifier<?>, YangInstanceIdentifier> iiCache = CacheBuilder.newBuilder()
+ .softValues().build(new CacheLoader<InstanceIdentifier<?>, YangInstanceIdentifier>() {
+
+ @Override
+ public YangInstanceIdentifier load(final InstanceIdentifier<?> key) throws Exception {
+ return toYangInstanceIdentifier(key);
+ }
+
+ });
public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
final BindingNormalizedNodeCodecRegistry codecRegistry) {
- this.classLoadingStrategy = classLoadingStrategy;
- this.codecRegistry = codecRegistry;
+ this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy,"classLoadingStrategy");
+ this.codecRegistry = Preconditions.checkNotNull(codecRegistry,"codecRegistry");
}
+ /**
+ * Translates supplied Binding Instance Identifier into NormalizedNode
+ * instance identifier.
+ *
+ * @param binding
+ * Binding Instance Identifier
+ * @return DOM Instance Identifier
+ * @throws IllegalArgumentException
+ * If supplied Instance Identifier is not valid.
+ */
public YangInstanceIdentifier toNormalized(final InstanceIdentifier<? extends DataObject> binding) {
return codecRegistry.toYangInstanceIdentifier(binding);
}
return codecRegistry.toYangInstanceIdentifier(binding);
}
+
+ YangInstanceIdentifier toYangInstanceIdentifierCached(final InstanceIdentifier<?> binding) {
+ return iiCache .getUnchecked(binding);
+ }
+
@Override
public <T extends DataObject> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
final InstanceIdentifier<T> path, final T data) {
return codecRegistry.toNormalizedNode(path, data);
}
+ /**
+ * Converts Binding Map.Entry to DOM Map.Entry
+ *
+ * Same as {@link #toNormalizedNode(InstanceIdentifier, DataObject)}.
+ *
+ * @param binding Map Entry with InstanceIdentifier as key and DataObject as value.
+ * @return DOM Map Entry with {@link YangInstanceIdentifier} as key and {@link NormalizedNode}
+ * as value.
+ */
@SuppressWarnings({"unchecked", "rawtypes"})
public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding) {
return ret.build();
}
+ protected ImmutableBiMap<Method, RpcDefinition> getRpcMethodToSchema(final Class<? extends RpcService> key) {
+ final QNameModule moduleName = BindingReflections.getQNameModule(key);
+ final Module module = runtimeContext.getSchemaContext().findModuleByNamespaceAndRevision(moduleName.getNamespace(), moduleName.getRevision());
+ final ImmutableBiMap.Builder<Method, RpcDefinition> ret = ImmutableBiMap.builder();
+ try {
+ for (final RpcDefinition rpcDef : module.getRpcs()) {
+ final Method method = findRpcMethod(key, rpcDef);
+ ret.put(method, rpcDef);
+ }
+ } catch (final NoSuchMethodException e) {
+ throw new IllegalStateException("Rpc defined in model does not have representation in generated class.", e);
+ }
+ return ret.build();
+ }
+
private Method findRpcMethod(final Class<? extends RpcService> key, final RpcDefinition rpcDef) throws NoSuchMethodException {
final String methodName = BindingMapping.getMethodName(rpcDef.getQName());
if(rpcDef.getInput() != null) {
return codecRegistry.create(context, bindingClasses);
}
- @Nonnull protected Map.Entry<InstanceIdentifier<?>, BindingCodecTreeNode<?>> getSubtreeCodec(
+ @Nonnull
+ protected Map.Entry<InstanceIdentifier<?>, BindingCodecTreeNode<?>> getSubtreeCodec(
final YangInstanceIdentifier domIdentifier) {
final BindingCodecTree currentCodecTree = codecRegistry.getCodecContext();
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.impl;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import java.lang.reflect.Method;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+abstract class ContextReferenceExtractor {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ContextReferenceExtractor.class);
+ private static final ContextReferenceExtractor NULL_EXTRACTOR = new ContextReferenceExtractor() {
+
+ @Override
+ InstanceIdentifier<?> extract(final DataObject obj) {
+ return null;
+ }
+ };
+
+
+ private static final LoadingCache<Class<?>, ContextReferenceExtractor> EXTRACTORS = CacheBuilder.newBuilder()
+ .weakKeys().build(new CacheLoader<Class<?>, ContextReferenceExtractor>() {
+
+ @Override
+ public ContextReferenceExtractor load(final Class<?> key) throws Exception {
+ return create(key);
+ }
+ });
+
+
+ private static final String GET_VALUE_NAME = "getValue";
+
+ static ContextReferenceExtractor from(final Class<?> obj) {
+ return EXTRACTORS.getUnchecked(obj);
+ }
+
+ /**
+ * Extract context-reference (Instance Identifier) from
+ * Binding DataObject.
+ *
+ * @param obj DataObject from which context reference
+ * should be extracted.
+ *
+ * @return Instance Identifier representing context reference
+ * or null, if data object does not contain context reference.
+ */
+ abstract @Nullable InstanceIdentifier<?> extract(DataObject obj);
+
+ private static @Nonnull ContextReferenceExtractor create(final Class<?> key) {
+ final Method contextGetter = getContextGetter(key);
+ if (contextGetter == null) {
+ return NULL_EXTRACTOR;
+ }
+ final Class<?> returnType = contextGetter.getReturnType();
+ try {
+ if (InstanceIdentifier.class.isAssignableFrom(returnType)) {
+ return DirectGetterRouteContextExtractor.create(contextGetter);
+ }
+ final Method getValueMethod = findGetValueMethod(returnType,InstanceIdentifier.class);
+ if (getValueMethod != null) {
+ return GetValueRouteContextExtractor.create(contextGetter, getValueMethod);
+ } else {
+ LOG.warn("Class {} can not be used to determine context, falling back to NULL_EXTRACTOR.",returnType);
+ }
+ } catch (final IllegalAccessException e) {
+ LOG.warn("Class {} does not conform to Binding Specification v1. Falling back to NULL_EXTRACTOR", e);
+ }
+ return NULL_EXTRACTOR;
+ }
+
+ private static @Nullable Method findGetValueMethod(final Class<?> type, final Class<?> returnType) {
+ try {
+ final Method method = type.getMethod(GET_VALUE_NAME);
+ if(returnType.equals(method.getReturnType())) {
+ return method;
+ }
+ } catch (final NoSuchMethodException e) {
+ LOG.warn("Value class {} does not comform to Binding Specification v1.", type, e);
+ }
+ return null;
+ }
+
+ private static Method getContextGetter(final Class<?> key) {
+ for (final Method method : key.getMethods()) {
+ if (method.getAnnotation(RoutingContext.class) != null) {
+ return method;
+ }
+ }
+ return null;
+ }
+
+
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.impl;
+
+import com.google.common.base.Throwables;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Method;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+final class DirectGetterRouteContextExtractor extends ContextReferenceExtractor {
+
+ private final static Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup();
+ private final MethodHandle handle;
+
+ private DirectGetterRouteContextExtractor(final MethodHandle rawHandle) {
+ handle = rawHandle.asType(MethodType.methodType(InstanceIdentifier.class, DataObject.class));
+ }
+
+ static final ContextReferenceExtractor create(final Method getterMethod) throws IllegalAccessException {
+ final MethodHandle getterHandle = PUBLIC_LOOKUP.unreflect(getterMethod);
+ return new DirectGetterRouteContextExtractor(getterHandle);
+ }
+
+ @Override
+ InstanceIdentifier<?> extract(final DataObject obj) {
+ try {
+ return (InstanceIdentifier<?>) handle.invokeExact(obj);
+ } catch (final Throwable e) {
+ throw Throwables.propagate(e);
+ }
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.impl;
+
+import com.google.common.base.Throwables;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Method;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+final class GetValueRouteContextExtractor extends ContextReferenceExtractor {
+
+ private final static Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup();
+ private final MethodHandle contextHandle;
+ private final MethodHandle valueHandle;
+
+ private GetValueRouteContextExtractor(final MethodHandle rawContextHandle, final MethodHandle rawValueHandle) {
+ contextHandle = rawContextHandle.asType(MethodType.methodType(Object.class, DataObject.class));
+ valueHandle = rawValueHandle.asType(MethodType.methodType(InstanceIdentifier.class, Object.class));
+ }
+
+ public static ContextReferenceExtractor create(final Method contextGetter, final Method getValueMethod)
+ throws IllegalAccessException {
+ final MethodHandle rawContextHandle = PUBLIC_LOOKUP.unreflect(contextGetter);
+ final MethodHandle rawValueHandle = PUBLIC_LOOKUP.unreflect(getValueMethod);
+ return new GetValueRouteContextExtractor(rawContextHandle, rawValueHandle);
+ }
+
+ @Override
+ InstanceIdentifier<?> extract(final DataObject obj) {
+ try {
+ final Object ctx = contextHandle.invokeExact(obj);
+ if (ctx != null) {
+ return (InstanceIdentifier<?>) valueHandle.invokeExact(ctx);
+ }
+ return null;
+ } catch (final Throwable e) {
+ throw Throwables.propagate(e);
+ }
+ }
+
+
+}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
+ * This program and the accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.md.sal.binding.impl;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
/**
*
private BindingNormalizedNodeCodecRegistry registry;
private ContainerNode domData;
- LazySerializedContainerNode(QName identifier, DataObject binding,
- BindingNormalizedNodeCodecRegistry registry) {
+ private LazySerializedContainerNode(final QName identifier, final DataObject binding,
+ final BindingNormalizedNodeCodecRegistry registry) {
this.identifier = new NodeIdentifier(identifier);
this.bindingData = binding;
this.registry = registry;
this.domData = null;
}
+ static NormalizedNode<?, ?> create(final SchemaPath rpcName, final DataObject data,
+ final BindingNormalizedNodeCodecRegistry codec) {
+ return new LazySerializedContainerNode(rpcName.getLastComponent(), data, codec);
+ }
+
+ static NormalizedNode<?, ?> withContextRef(final SchemaPath rpcName, final DataObject data,
+ final LeafNode<?> contextRef, final BindingNormalizedNodeCodecRegistry codec) {
+ return new WithContextRef(rpcName.getLastComponent(), data, contextRef, codec);
+ }
+
@Override
public Map<QName, String> getAttributes() {
return delegate().getAttributes();
}
private ContainerNode delegate() {
- if(domData == null) {
+ if (domData == null) {
domData = registry.toNormalizedNodeRpcData(bindingData);
registry = null;
}
}
@Override
- public QName getNodeType() {
- return delegate().getNodeType();
+ public final QName getNodeType() {
+ return identifier.getNodeType();
}
@Override
- public Collection<DataContainerChild<? extends PathArgument, ?>> getValue() {
+ public final Collection<DataContainerChild<? extends PathArgument, ?>> getValue() {
return delegate().getValue();
}
@Override
- public NodeIdentifier getIdentifier() {
+ public final NodeIdentifier getIdentifier() {
return identifier;
}
@Override
- public Optional<DataContainerChild<? extends PathArgument, ?>> getChild(PathArgument child) {
+ public Optional<DataContainerChild<? extends PathArgument, ?>> getChild(final PathArgument child) {
return delegate().getChild(child);
}
@Override
- public Object getAttributeValue(QName name) {
+ public final Object getAttributeValue(final QName name) {
return delegate().getAttributeValue(name);
}
- public DataObject bindingData() {
+ final DataObject bindingData() {
return bindingData;
}
+ /**
+ * Lazy Serialized Node with pre-cached serialized leaf holding routing information.
+ *
+ */
+ private static final class WithContextRef extends LazySerializedContainerNode {
+
+ private final LeafNode<?> contextRef;
+
+ protected WithContextRef(final QName identifier, final DataObject binding, final LeafNode<?> contextRef,
+ final BindingNormalizedNodeCodecRegistry registry) {
+ super(identifier, binding, registry);
+ this.contextRef = contextRef;
+ }
+
+ @Override
+ public Optional<DataContainerChild<? extends PathArgument, ?>> getChild(final PathArgument child) {
+ /*
+ * Use precached value of routing field and do not run full serialization if we are
+ * accessing it.
+ */
+ if (contextRef.getIdentifier().equals(child)) {
+ return Optional.<DataContainerChild<? extends PathArgument, ?>>of(contextRef);
+ }
+ return super.getChild(child);
+ }
+ }
+
}
/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
+ * This program and the accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.md.sal.binding.impl;
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
+import java.util.Map.Entry;
+import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
+import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
+import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+import org.opendaylight.controller.md.sal.dom.broker.spi.rpc.RpcRoutingStrategy;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
+import org.opendaylight.yangtools.yang.binding.DataContainer;
import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
class RpcServiceAdapter implements InvocationHandler {
- interface InvocationDelegate {
-
- ListenableFuture<RpcResult<?>> invoke(SchemaPath rpc, DataObject dataObject);
+ private final ImmutableMap<Method, RpcInvocationStrategy> rpcNames;
+ private final Class<? extends RpcService> type;
+ private final BindingToNormalizedNodeCodec codec;
+ private final DOMRpcService delegate;
+ private final RpcService proxy;
+ RpcServiceAdapter(final Class<? extends RpcService> type, final BindingToNormalizedNodeCodec codec,
+ final DOMRpcService domService) {
+ this.type = Preconditions.checkNotNull(type);
+ this.codec = Preconditions.checkNotNull(codec);
+ this.delegate = Preconditions.checkNotNull(domService);
+ final ImmutableMap.Builder<Method, RpcInvocationStrategy> rpcBuilder = ImmutableMap.builder();
+ for (final Entry<Method, RpcDefinition> rpc : codec.getRpcMethodToSchema(type).entrySet()) {
+ rpcBuilder.put(rpc.getKey(), createStrategy(rpc.getKey(), rpc.getValue()));
+ }
+ rpcNames = rpcBuilder.build();
+ proxy = (RpcService) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, this);
}
- private final RpcService proxy;
- private final ImmutableMap<Method,SchemaPath> rpcNames;
- private final Class<? extends RpcService> type;
- private final InvocationDelegate delegate;
+ private final ListenableFuture<RpcResult<?>> invoke0(final SchemaPath schemaPath, final NormalizedNode<?, ?> input) {
+ final CheckedFuture<DOMRpcResult, DOMRpcException> result = delegate.invokeRpc(schemaPath, input);
+ return transformFuture(schemaPath, result, codec.getCodecFactory());
+ }
- RpcServiceAdapter(Class<? extends RpcService> type, ImmutableMap<Method, SchemaPath> rpcNames, InvocationDelegate delegate) {
- this.rpcNames = rpcNames;
- this.type = type;
- this.delegate = delegate;
- this.proxy = (RpcService) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, this);
+ private RpcInvocationStrategy createStrategy(final Method method, final RpcDefinition schema) {
+ final RpcRoutingStrategy strategy = RpcRoutingStrategy.from(schema);
+ if (strategy.isContextBasedRouted()) {
+ return new RoutedStrategy(schema.getPath(), method, strategy.getLeaf());
+ }
+ return new NonRoutedStrategy(schema.getPath());
}
RpcService getProxy() {
}
@Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
- SchemaPath rpc = rpcNames.get(method);
- if(rpc != null) {
- if(method.getParameterTypes().length == 0) {
- return delegate.invoke(rpc, null);
+ final RpcInvocationStrategy rpc = rpcNames.get(method);
+ if (rpc != null) {
+ if (method.getParameterTypes().length == 0) {
+ return rpc.invokeEmpty();
}
- if(args.length != 1) {
+ if (args.length != 1) {
throw new IllegalArgumentException("Input must be provided.");
}
- return delegate.invoke(rpc,(DataObject) args[0]);
+ return rpc.invoke((DataObject) args[0]);
}
- if(isObjectMethod(method)) {
+ if (isObjectMethod(method)) {
return callObjectMethod(proxy, method, args);
}
throw new UnsupportedOperationException("Method " + method.toString() + "is unsupported.");
}
- private static boolean isObjectMethod(Method m) {
+ private static boolean isObjectMethod(final Method m) {
switch (m.getName()) {
- case "toString":
- return (m.getReturnType() == String.class && m.getParameterTypes().length == 0);
- case "hashCode":
- return (m.getReturnType() == int.class && m.getParameterTypes().length == 0);
- case "equals":
- return (m.getReturnType() == boolean.class && m.getParameterTypes().length == 1 && m.getParameterTypes()[0] == Object.class);
+ case "toString":
+ return (m.getReturnType() == String.class && m.getParameterTypes().length == 0);
+ case "hashCode":
+ return (m.getReturnType() == int.class && m.getParameterTypes().length == 0);
+ case "equals":
+ return (m.getReturnType() == boolean.class && m.getParameterTypes().length == 1 && m
+ .getParameterTypes()[0] == Object.class);
}
return false;
}
- private Object callObjectMethod(Object self, Method m, Object[] args) {
+ private Object callObjectMethod(final Object self, final Method m, final Object[] args) {
switch (m.getName()) {
- case "toString":
- return type.getName() + "$Adapter{delegate=" + delegate.toString()+"}";
- case "hashCode":
- return System.identityHashCode(self);
- case "equals":
- return (self == args[0]);
+ case "toString":
+ return type.getName() + "$Adapter{delegate=" + delegate.toString() + "}";
+ case "hashCode":
+ return System.identityHashCode(self);
+ case "equals":
+ return (self == args[0]);
}
return null;
}
+
+ private static ListenableFuture<RpcResult<?>> transformFuture(final SchemaPath rpc,
+ final ListenableFuture<DOMRpcResult> domFuture, final BindingNormalizedNodeCodecRegistry codec) {
+ return Futures.transform(domFuture, new Function<DOMRpcResult, RpcResult<?>>() {
+ @Override
+ public RpcResult<?> apply(final DOMRpcResult input) {
+ if (input instanceof LazySerializedDOMRpcResult) {
+ return ((LazySerializedDOMRpcResult) input).bidningRpcResult();
+ }
+ final NormalizedNode<?, ?> domData = input.getResult();
+ final DataObject bindingResult;
+ if (domData != null) {
+ final SchemaPath rpcOutput = rpc.createChild(QName.create(rpc.getLastComponent(), "output"));
+ bindingResult = codec.fromNormalizedNodeRpcData(rpcOutput, (ContainerNode) domData);
+ } else {
+ bindingResult = null;
+ }
+ return RpcResult.class.cast(RpcResultBuilder.success(bindingResult).build());
+ }
+ });
+ }
+
+ private abstract class RpcInvocationStrategy {
+
+ private final SchemaPath rpcName;
+
+ protected RpcInvocationStrategy(final SchemaPath path) {
+ rpcName = path;
+ }
+
+ final ListenableFuture<RpcResult<?>> invoke(final DataObject input) {
+ return invoke0(rpcName, serialize(input));
+ }
+
+ abstract NormalizedNode<?, ?> serialize(DataObject input);
+
+ final ListenableFuture<RpcResult<?>> invokeEmpty() {
+ return invoke0(rpcName, null);
+ }
+
+ final SchemaPath getRpcName() {
+ return rpcName;
+ }
+
+ }
+
+ private final class NonRoutedStrategy extends RpcInvocationStrategy {
+
+ protected NonRoutedStrategy(final SchemaPath path) {
+ super(path);
+ }
+
+ @Override
+ NormalizedNode<?, ?> serialize(final DataObject input) {
+ return LazySerializedContainerNode.create(getRpcName(), input, codec.getCodecRegistry());
+ }
+
+ }
+
+ private final class RoutedStrategy extends RpcInvocationStrategy {
+
+ private final ContextReferenceExtractor refExtractor;
+ private final NodeIdentifier contextName;
+
+ protected RoutedStrategy(final SchemaPath path, final Method rpcMethod, final QName leafName) {
+ super(path);
+ final Class<? extends DataContainer> inputType = BindingReflections.resolveRpcInputClass(rpcMethod).get();
+ refExtractor = ContextReferenceExtractor.from(inputType);
+ this.contextName = new NodeIdentifier(leafName);
+ }
+
+ @Override
+ NormalizedNode<?, ?> serialize(final DataObject input) {
+ final InstanceIdentifier<?> bindingII = refExtractor.extract(input);
+ if (bindingII != null) {
+ final YangInstanceIdentifier yangII = codec.toYangInstanceIdentifierCached(bindingII);
+ final LeafNode<?> contextRef = ImmutableNodes.leafNode(contextName, yangII);
+ return LazySerializedContainerNode.withContextRef(getRpcName(), input, contextRef,
+ codec.getCodecRegistry());
+ }
+ return LazySerializedContainerNode.create(getRpcName(), input, codec.getCodecRegistry());
+ }
+
+ }
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.impl;
+
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+
+import org.junit.Test;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.rpcservice.rev140701.RockTheHouseInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.rpcservice.rev140701.RockTheHouseInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.EncapsulatedRoute;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.EncapsulatedRouteInGrouping;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.RoutedSimpleRouteInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.RoutedSimpleRouteInputBuilder;
+import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+public final class ContextExtractorTest {
+
+ public interface Transitive extends EncapsulatedRouteInGrouping {
+
+ }
+
+ private static final InstanceIdentifier<?> TEST_ROUTE = InstanceIdentifier.create(Top.class);
+ private static final Transitive TEST_GROUPING = new Transitive() {
+
+ @Override
+ public Class<? extends DataContainer> getImplementedInterface() {
+ return Transitive.class;
+ }
+
+ @Override
+ public EncapsulatedRoute getRoute() {
+ return new EncapsulatedRoute(TEST_ROUTE);
+ }
+ };
+
+ @Test
+ public void testNonRoutedExtraction() {
+ final ContextReferenceExtractor extractor = ContextReferenceExtractor.from(RockTheHouseInput.class);
+ final RockTheHouseInput input = new RockTheHouseInputBuilder().build();
+ final InstanceIdentifier<?> extractedValue = extractor.extract(input);
+ assertNull(extractedValue);
+ }
+
+ @Test
+ public void testRoutedSimpleExtraction() {
+ final ContextReferenceExtractor extractor = ContextReferenceExtractor.from(RoutedSimpleRouteInput.class);
+ final RoutedSimpleRouteInput input = new RoutedSimpleRouteInputBuilder().setRoute(TEST_ROUTE).build();
+ final InstanceIdentifier<?> extractedValue = extractor.extract(input);
+ assertSame(TEST_ROUTE,extractedValue);
+ }
+
+ @Test
+ public void testRoutedEncapsulatedExtraction() {
+ final ContextReferenceExtractor extractor = ContextReferenceExtractor.from(EncapsulatedRouteInGrouping.class);
+ final InstanceIdentifier<?> extractedValue = extractor.extract(TEST_GROUPING);
+ assertSame(TEST_ROUTE,extractedValue);
+
+ }
+
+ @Test
+ public void testRoutedEncapsulatedTransitiveExtraction() {
+ final ContextReferenceExtractor extractor = ContextReferenceExtractor.from(Transitive.class);
+ final InstanceIdentifier<?> extractedValue = extractor.extract(TEST_GROUPING);
+ assertSame(TEST_ROUTE,extractedValue);
+ }
+ }
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AbstractFuture;
-import com.google.common.util.concurrent.AbstractListeningExecutorService;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.TimeUnit;
import org.opendaylight.controller.cluster.databroker.AbstractDOMBroker;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
/**
* This executor is used to execute Future listener callback Runnables async.
*/
- private final ExecutorService clientFutureCallbackExecutor;
+ private final Executor clientFutureCallbackExecutor;
- /**
- * This executor is re-used internally in calls to Futures#addCallback to avoid the overhead
- * of Futures#addCallback creating a MoreExecutors#sameThreadExecutor for each call.
- */
- private final ExecutorService internalFutureCallbackExecutor = new SimpleSameThreadExecutor();
-
- public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, ExecutorService listenableFutureExecutor) {
+ public ConcurrentDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, Executor listenableFutureExecutor) {
super(datastores);
this.clientFutureCallbackExecutor = Preconditions.checkNotNull(listenableFutureExecutor);
}
}
@Override
- public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
+ protected CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
} else {
ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
- Futures.addCallback(canCommitFuture, this, internalFutureCallbackExecutor);
+ Futures.addCallback(canCommitFuture, this, MoreExecutors.directExecutor());
}
}
}
};
ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
- Futures.addCallback(canCommitFuture, futureCallback, internalFutureCallbackExecutor);
+ Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
}
private void doPreCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
doCommit(startTime, clientSubmitFuture, transaction, cohorts);
} else {
ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
- Futures.addCallback(preCommitFuture, this, internalFutureCallbackExecutor);
+ Futures.addCallback(preCommitFuture, this, MoreExecutors.directExecutor());
}
}
};
ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
- Futures.addCallback(preCommitFuture, futureCallback, internalFutureCallbackExecutor);
+ Futures.addCallback(preCommitFuture, futureCallback, MoreExecutors.directExecutor());
}
private void doCommit(final long startTime, final AsyncNotifyingSettableFuture clientSubmitFuture,
clientSubmitFuture.set();
} else {
ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
- Futures.addCallback(commitFuture, this, internalFutureCallbackExecutor);
+ Futures.addCallback(commitFuture, this, MoreExecutors.directExecutor());
}
}
};
ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
- Futures.addCallback(commitFuture, futureCallback, internalFutureCallbackExecutor);
+ Futures.addCallback(commitFuture, futureCallback, MoreExecutors.directExecutor());
}
- private void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
+ private static void handleException(final AsyncNotifyingSettableFuture clientSubmitFuture,
final DOMDataWriteTransaction transaction,
final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
final String phase, final TransactionCommitFailedExceptionMapper exMapper,
final Throwable t) {
- if(clientSubmitFuture.isDone()) {
+ if (clientSubmitFuture.isDone()) {
// We must have had failures from multiple cohorts.
return;
}
LOG.warn("Tx: {} Error during phase {}, starting Abort", transaction.getIdentifier(), phase, t);
- Exception e;
- if(t instanceof Exception) {
+ final Exception e;
+ if (t instanceof Exception) {
e = (Exception)t;
} else {
e = new RuntimeException("Unexpected error occurred", t);
@SuppressWarnings("unchecked")
ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
int i = 0;
- for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
+ for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
canCommitFutures[i++] = cohort.abort();
}
// what's interesting to the client.
clientSubmitFuture.setException(clientException);
}
- }, internalFutureCallbackExecutor);
+ }, MoreExecutors.directExecutor());
}
/**
*/
private static final ThreadLocal<Boolean> ON_TASK_COMPLETION_THREAD_TL = new ThreadLocal<Boolean>();
- private final ExecutorService listenerExecutor;
+ private final Executor listenerExecutor;
- AsyncNotifyingSettableFuture(ExecutorService listenerExecutor) {
- this.listenerExecutor = listenerExecutor;
+ AsyncNotifyingSettableFuture(Executor listenerExecutor) {
+ this.listenerExecutor = Preconditions.checkNotNull(listenerExecutor);
}
@Override
}
}
}
-
- /**
- * A simple same-thread executor without the internal locking overhead that
- * MoreExecutors#sameThreadExecutor has. The #execute method is the only one of concern - we
- * don't shutdown the executor so the other methods irrelevant.
- */
- private static class SimpleSameThreadExecutor extends AbstractListeningExecutorService {
-
- @Override
- public void execute(Runnable command) {
- command.run();
- }
-
- @Override
- public boolean awaitTermination(long arg0, TimeUnit arg1) throws InterruptedException {
- return true;
- }
-
- @Override
- public boolean isShutdown() {
- return false;
- }
-
- @Override
- public boolean isTerminated() {
- return false;
- }
-
- @Override
- public void shutdown() {
- }
-
- @Override
- public List<Runnable> shutdownNow() {
- return null;
- }
- }
}
@Override
public DOMStoreReadTransaction newReadOnlyTransaction() {
- return new TransactionProxy(actorContext, TransactionProxy.TransactionType.READ_ONLY);
+ return new TransactionProxy(actorContext, TransactionType.READ_ONLY);
}
@Override
public DOMStoreWriteTransaction newWriteOnlyTransaction() {
actorContext.acquireTxCreationPermit();
- return new TransactionProxy(actorContext, TransactionProxy.TransactionType.WRITE_ONLY);
+ return new TransactionProxy(actorContext, TransactionType.WRITE_ONLY);
}
@Override
public DOMStoreReadWriteTransaction newReadWriteTransaction() {
actorContext.acquireTxCreationPermit();
- return new TransactionProxy(actorContext, TransactionProxy.TransactionType.READ_WRITE);
+ return new TransactionProxy(actorContext, TransactionType.READ_WRITE);
}
@Override
ShardTransactionIdentifier transactionId, String transactionChainId,
short clientVersion ) {
- return transactionActorFactory.newShardTransaction(TransactionProxy.TransactionType.fromInt(transactionType),
+ return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
transactionId, transactionChainId, clientVersion);
}
"createSnapshot" + ++createSnapshotTransactionCounter);
ActorRef createSnapshotTransaction = transactionActorFactory.newShardTransaction(
- TransactionProxy.TransactionType.READ_ONLY, transactionID, "", DataStoreVersions.CURRENT_VERSION);
+ TransactionType.READ_ONLY, transactionID, "", DataStoreVersions.CURRENT_VERSION);
createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, actorRef);
}
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActorWithMetering;
-import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
import org.opendaylight.controller.cluster.datastore.exceptions.UnknownMessageException;
import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
import akka.actor.Props;
import akka.japi.Creator;
import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActor;
-import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChainReply;
this.shardActor = shardActor;
}
- ActorRef newShardTransaction(TransactionProxy.TransactionType type, ShardTransactionIdentifier transactionID,
+ ActorRef newShardTransaction(TransactionType type, ShardTransactionIdentifier transactionID,
String transactionChainID, short clientVersion) {
final AbstractShardDataTreeTransaction<?> transaction;
switch (type) {
State localState = currentState;
checkReadyState(localState);
- return new ChainedTransactionProxy(actorContext, TransactionProxy.TransactionType.READ_ONLY,
+ return new ChainedTransactionProxy(actorContext, TransactionType.READ_ONLY,
transactionChainId, localState.getPreviousReadyFutures());
}
@Override
public DOMStoreReadWriteTransaction newReadWriteTransaction() {
actorContext.acquireTxCreationPermit();
- return allocateWriteTransaction(TransactionProxy.TransactionType.READ_WRITE);
+ return allocateWriteTransaction(TransactionType.READ_WRITE);
}
@Override
public DOMStoreWriteTransaction newWriteOnlyTransaction() {
actorContext.acquireTxCreationPermit();
- return allocateWriteTransaction(TransactionProxy.TransactionType.WRITE_ONLY);
+ return allocateWriteTransaction(TransactionType.WRITE_ONLY);
}
@Override
actorContext.broadcast(new CloseTransactionChain(transactionChainId).toSerializable());
}
- private ChainedTransactionProxy allocateWriteTransaction(TransactionProxy.TransactionType type) {
+ private ChainedTransactionProxy allocateWriteTransaction(TransactionType type) {
State localState = currentState;
checkReadyState(localState);
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Future;
public class TransactionContextImpl extends AbstractTransactionContext {
private static final Logger LOG = LoggerFactory.getLogger(TransactionContextImpl.class);
- private final String transactionChainId;
private final ActorContext actorContext;
private final ActorSelection actor;
private final boolean isTxActorLocal;
private int totalBatchedModificationsSent;
protected TransactionContextImpl(ActorSelection actor, TransactionIdentifier identifier,
- String transactionChainId, ActorContext actorContext, SchemaContext schemaContext, boolean isTxActorLocal,
+ ActorContext actorContext, boolean isTxActorLocal,
short remoteTransactionVersion, OperationCompleter operationCompleter) {
super(identifier);
this.actor = actor;
- this.transactionChainId = transactionChainId;
this.actorContext = actorContext;
this.isTxActorLocal = isTxActorLocal;
this.remoteTransactionVersion = remoteTransactionVersion;
}
private BatchedModifications newBatchedModifications() {
- return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, transactionChainId);
+ return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, getIdentifier().getChainId());
}
private void batchModification(Modification modification) {
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.GuardedBy;
-import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
*/
public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier> implements DOMStoreReadWriteTransaction {
- public static enum TransactionType {
- READ_ONLY,
- WRITE_ONLY,
- READ_WRITE;
-
- // Cache all values
- private static final TransactionType[] VALUES = values();
-
- public static TransactionType fromInt(final int type) {
- try {
- return VALUES[type];
- } catch (IndexOutOfBoundsException e) {
- throw new IllegalArgumentException("In TransactionType enum value " + type, e);
- }
- }
- }
-
private static enum TransactionState {
OPEN,
READY,
private final TransactionType transactionType;
final ActorContext actorContext;
- private final String transactionChainId;
private final SchemaContext schemaContext;
private TransactionState state = TransactionState.OPEN;
}
public TransactionProxy(ActorContext actorContext, TransactionType transactionType, String transactionChainId) {
- super(createIdentifier(actorContext));
+ super(createIdentifier(actorContext, transactionChainId));
this.actorContext = Preconditions.checkNotNull(actorContext,
"actorContext should not be null");
this.transactionType = Preconditions.checkNotNull(transactionType,
"transactionType should not be null");
this.schemaContext = Preconditions.checkNotNull(actorContext.getSchemaContext(),
"schemaContext should not be null");
- this.transactionChainId = transactionChainId;
LOG.debug("Created txn {} of type {} on chain {}", getIdentifier(), transactionType, transactionChainId);
}
- private static TransactionIdentifier createIdentifier(ActorContext actorContext) {
+ private static TransactionIdentifier createIdentifier(ActorContext actorContext, String transactionChainId) {
String memberName = actorContext.getCurrentMemberName();
if (memberName == null) {
memberName = "UNKNOWN-MEMBER";
}
- return new TransactionIdentifier(memberName, counter.getAndIncrement());
+ return TransactionIdentifier.create(memberName, counter.getAndIncrement(), transactionChainId);
}
@VisibleForTesting
TransactionFutureCallback txFutureCallback = txFutureCallbackMap.values().iterator().next();
LOG.debug("Tx {} Readying transaction for shard {} on chain {}", getIdentifier(),
- txFutureCallback.getShardName(), transactionChainId);
+ txFutureCallback.getShardName(), getTransactionChainId());
final OperationCallback.Reference operationCallbackRef =
new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
for(TransactionFutureCallback txFutureCallback : txFutureCallbackMap.values()) {
LOG.debug("Tx {} Readying transaction for shard {} on chain {}", getIdentifier(),
- txFutureCallback.getShardName(), transactionChainId);
+ txFutureCallback.getShardName(), getTransactionChainId());
final TransactionContext transactionContext = txFutureCallback.getTransactionContext();
final Future<ActorSelection> future;
}
String getTransactionChainId() {
- return transactionChainId;
+ return getIdentifier().getChainId();
}
protected ActorContext getActorContext() {
if(remoteTransactionVersion < DataStoreVersions.LITHIUM_VERSION) {
return new PreLithiumTransactionContextImpl(transactionPath, transactionActor, getIdentifier(),
- transactionChainId, actorContext, schemaContext, isTxActorLocal, remoteTransactionVersion,
+ actorContext, isTxActorLocal, remoteTransactionVersion,
operationCompleter);
} else {
- return new TransactionContextImpl(transactionActor, getIdentifier(), transactionChainId,
- actorContext, schemaContext, isTxActorLocal, remoteTransactionVersion, operationCompleter);
+ return new TransactionContextImpl(transactionActor, getIdentifier(),
+ actorContext, isTxActorLocal, remoteTransactionVersion, operationCompleter);
}
}
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.datastore;
+
+public enum TransactionType {
+ READ_ONLY,
+ WRITE_ONLY,
+ READ_WRITE;
+
+ // Cache all values
+ private static final TransactionType[] VALUES = values();
+
+ public static TransactionType fromInt(final int type) {
+ try {
+ return VALUES[type];
+ } catch (IndexOutOfBoundsException e) {
+ throw new IllegalArgumentException("In TransactionType enum value " + type, e);
+ }
+ }
+}
\ No newline at end of file
import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Future;
private final String transactionPath;
public PreLithiumTransactionContextImpl(String transactionPath, ActorSelection actor, TransactionIdentifier identifier,
- String transactionChainId, ActorContext actorContext, SchemaContext schemaContext, boolean isTxActorLocal,
+ ActorContext actorContext, boolean isTxActorLocal,
short remoteTransactionVersion, OperationCompleter operationCompleter) {
- super(actor, identifier, transactionChainId, actorContext, schemaContext, isTxActorLocal,
- remoteTransactionVersion, operationCompleter);
+ super(actor, identifier, actorContext, isTxActorLocal, remoteTransactionVersion, operationCompleter);
this.transactionPath = transactionPath;
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.datastore.identifiers;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * A TransactionIdentifier which is tied to a backend transaction chain.
+ */
+public class ChainedTransactionIdentifier extends TransactionIdentifier {
+ private final String chainId;
+
+ public ChainedTransactionIdentifier(final String memberName, final long counter, final String chainId) {
+ super(memberName, counter);
+ this.chainId = Preconditions.checkNotNull(chainId);
+ }
+
+ @Override
+ public String getChainId() {
+ return chainId;
+ }
+}
package org.opendaylight.controller.cluster.datastore.identifiers;
import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
public class TransactionIdentifier {
private static final String TX_SEPARATOR = "-txn-";
this.counter = counter;
}
+ public String getChainId() {
+ return "";
+ }
+
+ public static TransactionIdentifier create(String memberName, long counter, String chainId) {
+ if (Strings.isNullOrEmpty(chainId)) {
+ return new TransactionIdentifier(memberName, counter);
+ } else {
+ return new ChainedTransactionIdentifier(memberName, counter, chainId);
+ }
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) {
import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
import org.opendaylight.controller.md.sal.common.util.jmx.QueuedNotificationManagerMXBeanImpl;
-import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStats;
import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStatsMXBeanImpl;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
-import org.opendaylight.yangtools.util.concurrent.ListenerNotificationQueueStats;
import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
return getOnDemandRaftState().getInMemoryJournalLogSize();
}
- @Override
- public ThreadExecutorStats getDataStoreExecutorStats() {
- // FIXME: this particular thing does not work, as it really is DS-specific
- return null;
- }
-
- @Override
- public ThreadExecutorStats getNotificationMgrExecutorStats() {
- return notificationExecutorStatsBean.toThreadExecutorStats();
- }
-
- @Override
- public List<ListenerNotificationQueueStats> getCurrentNotificationMgrListenerQueueStats() {
- return notificationManagerStatsBean.getCurrentListenerQueueStats();
- }
-
- @Override
- public int getMaxNotificationMgrListenerQueueSize() {
- return notificationManagerStatsBean.getMaxListenerQueueSize();
- }
-
/**
* resets the counters related to transactions
*/
import java.util.List;
import org.opendaylight.controller.cluster.raft.client.messages.FollowerInfo;
-import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStats;
-import org.opendaylight.yangtools.util.concurrent.ListenerNotificationQueueStats;
/**
* @author: syedbahm
boolean isSnapshotCaptureInitiated();
- ThreadExecutorStats getDataStoreExecutorStats();
-
- ThreadExecutorStats getNotificationMgrExecutorStats();
-
- List<ListenerNotificationQueueStats> getCurrentNotificationMgrListenerQueueStats();
-
- int getMaxNotificationMgrListenerQueueSize();
-
void resetTransactionCounters();
long getInMemoryJournalDataSize();
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
-import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
shard.tell(new CreateTransaction("txn-1",
- TransactionProxy.TransactionType.READ_ONLY.ordinal() ).toSerializable(), getRef());
+ TransactionType.READ_ONLY.ordinal() ).toSerializable(), getRef());
CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
CreateTransactionReply.class);
waitUntilLeader(shard);
shard.tell(new CreateTransaction("txn-1",
- TransactionProxy.TransactionType.READ_ONLY.ordinal() , "foobar").toSerializable(),
+ TransactionType.READ_ONLY.ordinal() , "foobar").toSerializable(),
getRef());
CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
// Create a read Tx on the same chain.
- shard.tell(new CreateTransaction(transactionID2, TransactionProxy.TransactionType.READ_ONLY.ordinal() ,
+ shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal() ,
transactionChainID).toSerializable(), getRef());
CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
-import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
import org.opendaylight.controller.cluster.datastore.node.utils.serialization.NormalizedNodeSerializer;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.opendaylight.controller.cluster.datastore.ShardWriteTransaction.GetCompositeModificationReply;
-import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
import org.opendaylight.controller.cluster.datastore.exceptions.UnknownMessageException;
import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType.READ_WRITE;
-import static org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType.WRITE_ONLY;
+import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_WRITE;
+import static org.opendaylight.controller.cluster.datastore.TransactionType.WRITE_ONLY;
import akka.actor.ActorRef;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
-import static org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType.READ_ONLY;
-import static org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType.READ_WRITE;
-import static org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType.WRITE_ONLY;
+import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_ONLY;
+import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_WRITE;
+import static org.opendaylight.controller.cluster.datastore.TransactionType.WRITE_ONLY;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
-import org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType;
import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
public void testGetIdentifier() {
setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
TransactionProxy transactionProxy = new TransactionProxy(mockActorContext,
- TransactionProxy.TransactionType.READ_ONLY);
+ TransactionType.READ_ONLY);
Object id = transactionProxy.getIdentifier();
assertNotNull("getIdentifier returned null", id);
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
-import static org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType.READ_WRITE;
-import static org.opendaylight.controller.cluster.datastore.TransactionProxy.TransactionType.WRITE_ONLY;
+import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_WRITE;
+import static org.opendaylight.controller.cluster.datastore.TransactionType.WRITE_ONLY;
import akka.actor.ActorRef;
import akka.dispatch.Futures;
import akka.util.Timeout;
import org.opendaylight.controller.cluster.datastore.Shard;
import org.opendaylight.controller.cluster.datastore.ShardTest;
import org.opendaylight.controller.cluster.datastore.ShardTestKit;
-import org.opendaylight.controller.cluster.datastore.TransactionProxy;
+import org.opendaylight.controller.cluster.datastore.TransactionType;
import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
String transactionID = "txn-1";
shard.tell(ShardTransactionMessages.CreateTransaction.newBuilder()
.setTransactionId(transactionID)
- .setTransactionType(TransactionProxy.TransactionType.WRITE_ONLY.ordinal())
+ .setTransactionType(TransactionType.WRITE_ONLY.ordinal())
.setTransactionChainId("").build(), getRef());
final FiniteDuration duration = duration("5 seconds");
String transactionID = "txn-1";
shard.tell(ShardTransactionMessages.CreateTransaction.newBuilder()
.setTransactionId(transactionID)
- .setTransactionType(TransactionProxy.TransactionType.WRITE_ONLY.ordinal())
+ .setTransactionType(TransactionType.WRITE_ONLY.ordinal())
.setTransactionChainId("").build(), getRef());
final FiniteDuration duration = duration("5 seconds");
LOG.debug("Create rpc registry and broker actors");
rpcRegistry =
- getContext().actorOf(Props.create(RpcRegistry.class).
+ getContext().actorOf(RpcRegistry.props().
withMailbox(config.getMailBoxName()), config.getRpcRegistryName());
rpcBroker =
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
+
import org.opendaylight.controller.remote.rpc.registry.gossip.Copier;
import org.opendaylight.controller.sal.connector.api.RpcRouter;
}
}
+ public Set<RpcRouter.RouteIdentifier<?, ?, ?>> getRoutes() {
+ return table.keySet();
+ }
+
public void addRoute(RpcRouter.RouteIdentifier<?,?,?> routeId){
table.put(routeId, System.currentTimeMillis());
}
package org.opendaylight.controller.remote.rpc.registry;
import akka.actor.ActorRef;
+import akka.actor.Props;
+import akka.japi.Creator;
import akka.japi.Option;
import akka.japi.Pair;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.remote.rpc.registry.RpcRegistry.Messages.SetLocalRouter;
import org.opendaylight.controller.remote.rpc.registry.gossip.Bucket;
import org.opendaylight.controller.remote.rpc.registry.gossip.BucketStore;
+import org.opendaylight.controller.remote.rpc.registry.mbeans.RemoteRpcRegistryMXBean;
+import org.opendaylight.controller.remote.rpc.registry.mbeans.RemoteRpcRegistryMXBeanImpl;
import org.opendaylight.controller.sal.connector.api.RpcRouter;
import org.opendaylight.controller.sal.connector.api.RpcRouter.RouteIdentifier;
getLocalBucket().setData(new RoutingTable());
}
+ public static Props props() {
+ return Props.create(new RpcRegistryCreator());
+ }
+
@Override
protected void handleReceive(Object message) throws Exception {
//TODO: if sender is remote, reject message
}
}
}
+
+ private static class RpcRegistryCreator implements Creator<RpcRegistry> {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public RpcRegistry create() throws Exception {
+ RpcRegistry registry = new RpcRegistry();
+ RemoteRpcRegistryMXBean mxBean = new RemoteRpcRegistryMXBeanImpl(registry);
+ return registry;
+ }
+ }
}
import akka.actor.Address;
import akka.actor.Props;
import akka.cluster.ClusterActorRefProvider;
-import com.google.common.annotations.VisibleForTesting;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
}
}
- protected BucketImpl<T> getLocalBucket() {
+ public BucketImpl<T> getLocalBucket() {
return localBucket;
}
versions.put(selfAddress, localBucket.getVersion());
}
- protected Map<Address, Bucket<T>> getRemoteBuckets() {
+ public Map<Address, Bucket<T>> getRemoteBuckets() {
return remoteBuckets;
}
- @VisibleForTesting
- Map<Address, Long> getVersions() {
+ public Map<Address, Long> getVersions() {
return versions;
}
}
--- /dev/null
+package org.opendaylight.controller.remote.rpc.registry.mbeans;
+
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * JMX bean to check remote rpc registry
+ */
+
+public interface RemoteRpcRegistryMXBean {
+
+ Set<String> getGlobalRpc();
+
+ String getBucketVersions();
+
+ Set<String> getLocalRegisteredRoutedRpc();
+
+ Map<String,String> findRpcByName(String name);
+
+ Map<String,String> findRpcByRoute(String route);
+}
--- /dev/null
+package org.opendaylight.controller.remote.rpc.registry.mbeans;
+
+import akka.actor.Address;
+import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
+import org.opendaylight.controller.remote.rpc.registry.RoutingTable;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
+import org.opendaylight.controller.remote.rpc.registry.gossip.Bucket;
+import org.opendaylight.controller.sal.connector.api.RpcRouter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+
+public class RemoteRpcRegistryMXBeanImpl extends AbstractMXBean implements RemoteRpcRegistryMXBean {
+
+ protected final Logger log = LoggerFactory.getLogger(getClass());
+
+ private final String NULL_CONSTANT = "null";
+
+ private final String LOCAL_CONSTANT = "local";
+
+ private final String ROUTE_CONSTANT = "route:";
+
+ private final String NAME_CONSTANT = " | name:";
+
+ private final RpcRegistry rpcRegistry;
+
+ public RemoteRpcRegistryMXBeanImpl(final RpcRegistry rpcRegistry) {
+ super("RemoteRpcRegistry", "RemoteRpcBroker", null);
+ this.rpcRegistry = rpcRegistry;
+ registerMBean();
+ }
+
+ @Override
+ public Set<String> getGlobalRpc() {
+ RoutingTable table = rpcRegistry.getLocalBucket().getData();
+ Set<String> globalRpc = new HashSet<>(table.getRoutes().size());
+ for(RpcRouter.RouteIdentifier<?, ?, ?> route : table.getRoutes()){
+ if(route.getRoute() == null) {
+ globalRpc.add(route.getType() != null ? route.getType().toString() : NULL_CONSTANT);
+ }
+ }
+ if(log.isDebugEnabled()) {
+ log.debug("Locally registered global RPCs {}", globalRpc);
+ }
+ return globalRpc;
+ }
+
+ @Override
+ public Set<String> getLocalRegisteredRoutedRpc() {
+ RoutingTable table = rpcRegistry.getLocalBucket().getData();
+ Set<String> routedRpc = new HashSet<>(table.getRoutes().size());
+ for(RpcRouter.RouteIdentifier<?, ?, ?> route : table.getRoutes()){
+ if(route.getRoute() != null) {
+ StringBuilder builder = new StringBuilder(ROUTE_CONSTANT);
+ builder.append(route.getRoute().toString()).append(NAME_CONSTANT).append(route.getType() != null ?
+ route.getType().toString() : NULL_CONSTANT);
+ routedRpc.add(builder.toString());
+ }
+ }
+ if(log.isDebugEnabled()) {
+ log.debug("Locally registered routed RPCs {}", routedRpc);
+ }
+ return routedRpc;
+ }
+
+ @Override
+ public Map<String, String> findRpcByName(final String name) {
+ RoutingTable localTable = rpcRegistry.getLocalBucket().getData();
+ // Get all RPCs from local bucket
+ Map<String, String> rpcMap = new HashMap<>(getRpcMemberMapByName(localTable, name, LOCAL_CONSTANT));
+
+ // Get all RPCs from remote bucket
+ Map<Address, Bucket<RoutingTable>> buckets = rpcRegistry.getRemoteBuckets();
+ for(Address address : buckets.keySet()) {
+ RoutingTable table = buckets.get(address).getData();
+ rpcMap.putAll(getRpcMemberMapByName(table, name, address.toString()));
+ }
+ if(log.isDebugEnabled()) {
+ log.debug("list of RPCs {} searched by name {}", rpcMap, name);
+ }
+ return rpcMap;
+ }
+
+ @Override
+ public Map<String, String> findRpcByRoute(String routeId) {
+ RoutingTable localTable = rpcRegistry.getLocalBucket().getData();
+ Map<String, String> rpcMap = new HashMap<>(getRpcMemberMapByRoute(localTable, routeId, LOCAL_CONSTANT));
+
+ Map<Address, Bucket<RoutingTable>> buckets = rpcRegistry.getRemoteBuckets();
+ for(Address address : buckets.keySet()) {
+ RoutingTable table = buckets.get(address).getData();
+ rpcMap.putAll(getRpcMemberMapByRoute(table, routeId, address.toString()));
+
+ }
+ if(log.isDebugEnabled()) {
+ log.debug("list of RPCs {} searched by route {}", rpcMap, routeId);
+ }
+ return rpcMap;
+ }
+
+ /**
+ * Search if the routing table route String contains routeName
+ */
+
+ private Map<String,String> getRpcMemberMapByRoute(final RoutingTable table, final String routeName,
+ final String address) {
+ Set<RpcRouter.RouteIdentifier<?, ?, ?>> routes = table.getRoutes();
+ Map<String, String> rpcMap = new HashMap<>(routes.size());
+ for(RpcRouter.RouteIdentifier<?, ?, ?> route : table.getRoutes()){
+ if(route.getRoute() != null) {
+ String routeString = route.getRoute().toString();
+ if(routeString.contains(routeName)) {
+ StringBuilder builder = new StringBuilder(ROUTE_CONSTANT);
+ builder.append(routeString).append(NAME_CONSTANT).append(route.getType() != null ?
+ route.getType().toString() : NULL_CONSTANT);
+ rpcMap.put(builder.toString(), address);
+ }
+ }
+ }
+ return rpcMap;
+ }
+
+ /**
+ * Search if the routing table route type contains name
+ */
+ private Map<String, String> getRpcMemberMapByName(final RoutingTable table, final String name,
+ final String address) {
+ Set<RpcRouter.RouteIdentifier<?, ?, ?>> routes = table.getRoutes();
+ Map<String, String> rpcMap = new HashMap<>(routes.size());
+ for(RpcRouter.RouteIdentifier<?, ?, ?> route : routes){
+ if(route.getType() != null) {
+ String type = route.getType().toString();
+ if(type.contains(name)) {
+ StringBuilder builder = new StringBuilder(ROUTE_CONSTANT);
+ builder.append(route.getRoute() != null ? route.getRoute().toString(): NULL_CONSTANT)
+ .append(NAME_CONSTANT).append(type);
+ rpcMap.put(builder.toString(), address);
+ }
+ }
+ }
+ return rpcMap;
+ }
+
+
+
+ @Override
+ public String getBucketVersions() {
+ return rpcRegistry.getVersions().toString();
+ }
+
+}
\ No newline at end of file
result = partialResult;
}
return new NormalizedNodeContext(path,result);
+ } catch (final RestconfDocumentedException e) {
+ throw e;
} catch (final Exception e) {
LOG.debug("Error parsing json input", e);
final NormalizedNode<?, ?> result = parse(path,doc);
return new NormalizedNodeContext(path,result);
+ } catch (final RestconfDocumentedException e){
+ throw e;
} catch (final Exception e) {
LOG.debug("Error parsing xml input", e);
final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
final Module latestModule = globalSchema.findModuleByName(startModule, null);
+
+ if (latestModule == null) {
+ throw new RestconfDocumentedException("The module named '" + startModule + "' does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
+ }
+
final InstanceIdentifierContext<?> iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
toMountPointIdentifier);
return retValue;
}
throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
- }
- catch (final InterruptedException e) {
+ } catch (final InterruptedException e) {
throw new RestconfDocumentedException(
"The operation was interrupted while executing and did not complete.", ErrorType.RPC,
ErrorTag.PARTIAL_OPERATION);
- }
- catch (final ExecutionException e) {
+ } catch (final ExecutionException e) {
Throwable cause = e.getCause();
- if (cause instanceof CancellationException) {
- throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
- ErrorTag.PARTIAL_OPERATION);
- } else if (cause != null) {
+ if (cause != null) {
while (cause.getCause() != null) {
cause = cause.getCause();
}
throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
e);
}
+ } catch (final CancellationException e) {
+ throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
+ ErrorTag.PARTIAL_OPERATION);
}
}
import java.util.Collection;
import java.util.Collections;
import org.opendaylight.controller.config.yang.md.sal.rest.connector.Config;
+import org.opendaylight.controller.config.yang.md.sal.rest.connector.Delete;
import org.opendaylight.controller.config.yang.md.sal.rest.connector.Get;
import org.opendaylight.controller.config.yang.md.sal.rest.connector.Operational;
import org.opendaylight.controller.config.yang.md.sal.rest.connector.Post;
@Override
public Config getConfig() {
final Config config = new Config();
+
final Get get = new Get();
get.setReceivedRequests(stats.getConfigGet());
+ get.setSuccessfulResponses(stats.getSuccessGetConfig());
+ get.setFailedResponses(stats.getFailureGetConfig());
config.setGet(get);
+
final Post post = new Post();
post.setReceivedRequests(stats.getConfigPost());
+ post.setSuccessfulResponses(stats.getSuccessPost());
+ post.setFailedResponses(stats.getFailurePost());
config.setPost(post);
+
final Put put = new Put();
put.setReceivedRequests(stats.getConfigPut());
+ put.setSuccessfulResponses(stats.getSuccessPut());
+ put.setFailedResponses(stats.getFailurePut());
config.setPut(put);
+
+ final Delete delete = new Delete();
+ delete.setReceivedRequests(stats.getConfigDelete());
+ delete.setSuccessfulResponses(stats.getSuccessDelete());
+ delete.setFailedResponses(stats.getFailureDelete());
+ config.setDelete(delete);
+
return config;
}
final Operational operational = new Operational();
final Get get = new Get();
get.setReceivedRequests(opGet);
+ get.setSuccessfulResponses(stats.getSuccessGetOperational());
+ get.setFailedResponses(stats.getFailureGetOperational());
operational.setGet(get);
return operational;
}
final BigInteger rpcInvoke = stats.getRpc();
final Rpcs rpcs = new Rpcs();
rpcs.setReceivedRequests(rpcInvoke);
- return rpcs ;
+ return rpcs;
}
-}
+}
\ No newline at end of file
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.opendaylight.controller.sal.rest.api.RestconfService;
AtomicLong configPost = new AtomicLong();
AtomicLong configPut = new AtomicLong();
AtomicLong configDelete = new AtomicLong();
+ AtomicLong successGetConfig = new AtomicLong();
+ AtomicLong successGetOperational = new AtomicLong();
+ AtomicLong successPost = new AtomicLong();
+ AtomicLong successPut = new AtomicLong();
+ AtomicLong successDelete = new AtomicLong();
+ AtomicLong failureGetConfig = new AtomicLong();
+ AtomicLong failureGetOperational = new AtomicLong();
+ AtomicLong failurePost = new AtomicLong();
+ AtomicLong failurePut = new AtomicLong();
+ AtomicLong failureDelete = new AtomicLong();
private static final StatisticsRestconfServiceWrapper INSTANCE = new StatisticsRestconfServiceWrapper(RestconfImpl.getInstance());
@Override
public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
configGet.incrementAndGet();
- return delegate.readConfigurationData(identifier, uriInfo);
+ NormalizedNodeContext normalizedNodeContext = null;
+ try {
+ normalizedNodeContext = delegate.readConfigurationData(identifier, uriInfo);
+ if (normalizedNodeContext.getData() != null) {
+ successGetConfig.incrementAndGet();
+ }
+ else {
+ failureGetConfig.incrementAndGet();
+ }
+ } catch (Exception e) {
+ failureGetConfig.incrementAndGet();
+ throw e;
+ }
+ return normalizedNodeContext;
}
@Override
public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
operationalGet.incrementAndGet();
- return delegate.readOperationalData(identifier, uriInfo);
+ NormalizedNodeContext normalizedNodeContext = null;
+ try {
+ normalizedNodeContext = delegate.readOperationalData(identifier, uriInfo);
+ if (normalizedNodeContext.getData() != null) {
+ successGetOperational.incrementAndGet();
+ }
+ else {
+ failureGetOperational.incrementAndGet();
+ }
+ } catch (Exception e) {
+ failureGetOperational.incrementAndGet();
+ throw e;
+ }
+ return normalizedNodeContext;
}
@Override
public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
configPut.incrementAndGet();
- return delegate.updateConfigurationData(identifier, payload);
+ Response response = null;
+ try {
+ response = delegate.updateConfigurationData(identifier, payload);
+ if (response.getStatus() == Status.OK.getStatusCode()) {
+ successPut.incrementAndGet();
+ }
+ else {
+ failurePut.incrementAndGet();
+ }
+ } catch (Exception e) {
+ failurePut.incrementAndGet();
+ throw e;
+ }
+ return response;
}
@Override
public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
configPost.incrementAndGet();
- return delegate.createConfigurationData(identifier, payload, uriInfo);
+ Response response = null;
+ try {
+ response = delegate.createConfigurationData(identifier, payload, uriInfo);
+ if (response.getStatus() == Status.OK.getStatusCode()) {
+ successPost.incrementAndGet();
+ }
+ else {
+ failurePost.incrementAndGet();
+ }
+ } catch (Exception e) {
+ failurePost.incrementAndGet();
+ throw e;
+ }
+ return response;
}
@Override
public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
configPost.incrementAndGet();
- return delegate.createConfigurationData(payload, uriInfo);
+ Response response = null;
+ try {
+ response = delegate.createConfigurationData(payload, uriInfo);
+ if (response.getStatus() == Status.OK.getStatusCode()) {
+ successPost.incrementAndGet();
+ }
+ else {
+ failurePost.incrementAndGet();
+ }
+ }catch (Exception e) {
+ failurePost.incrementAndGet();
+ throw e;
+ }
+ return response;
}
@Override
public Response deleteConfigurationData(final String identifier) {
- return delegate.deleteConfigurationData(identifier);
+ configDelete.incrementAndGet();
+ Response response = null;
+ try {
+ response = delegate.deleteConfigurationData(identifier);
+ if (response.getStatus() == Status.OK.getStatusCode()) {
+ successDelete.incrementAndGet();
+ }
+ else {
+ failureDelete.incrementAndGet();
+ }
+ } catch (Exception e) {
+ failureDelete.incrementAndGet();
+ throw e;
+ }
+ return response;
}
@Override
public BigInteger getRpc() {
return BigInteger.valueOf(rpc.get());
}
-}
+
+ public BigInteger getSuccessGetConfig() {
+ return BigInteger.valueOf(successGetConfig.get());
+ }
+
+ public BigInteger getSuccessGetOperational() {
+ return BigInteger.valueOf(successGetOperational.get());
+ }
+
+ public BigInteger getSuccessPost() {
+ return BigInteger.valueOf(successPost.get());
+ }
+
+ public BigInteger getSuccessPut() {
+ return BigInteger.valueOf(successPut.get());
+ }
+
+ public BigInteger getSuccessDelete() {
+ return BigInteger.valueOf(successDelete.get());
+ }
+
+ public BigInteger getFailureGetConfig() {
+ return BigInteger.valueOf(failureGetConfig.get());
+ }
+
+ public BigInteger getFailureGetOperational() {
+ return BigInteger.valueOf(failureGetOperational.get());
+ }
+
+ public BigInteger getFailurePost() {
+ return BigInteger.valueOf(failurePost.get());
+ }
+
+ public BigInteger getFailurePut() {
+ return BigInteger.valueOf(failurePut.get());
+ }
+
+ public BigInteger getFailureDelete() {
+ return BigInteger.valueOf(failureDelete.get());
+ }
+}
\ No newline at end of file
leaf received-requests {
type uint64;
}
+
+ leaf successful-responses {
+ type uint64;
+ }
+
+ leaf failed-responses {
+ type uint64;
+ }
}
augment "/config:modules/config:module/config:configuration" {
container put {
uses statistics;
}
+
+ container delete {
+ uses statistics;
+ }
}
container operational {
}
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- final SoftReference<YangStoreSnapshot> yangStoreSnapshotSoftReference = ref.get();
- YangStoreContext ret = yangStoreSnapshotSoftReference != null ? yangStoreSnapshotSoftReference.get() : null;
- if(ret == null) {
- ret = getYangStoreSnapshot();
+ YangStoreContext context = ref.get().get();
+
+ if(context == null) {
+ context = getYangStoreSnapshot();
}
this.listeners.add(listener);
- listener.onCapabilitiesAdded(NetconfOperationServiceFactoryImpl.setupCapabilities(ret));
+ listener.onCapabilitiesAdded(NetconfOperationServiceFactoryImpl.setupCapabilities(context));
return new AutoCloseable() {
@Override
<password>admin</password>
</module>
+
+ <!--TCP endpoint for MD-SAL netconf server -->
+ <!--<module>-->
+ <!--<type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netconf:northbound:tcp">prefix:netconf-northbound-tcp</type>-->
+ <!--<name>netconf-mdsal-tcp-server</name>-->
+ <!--<dispatcher xmlns="urn:opendaylight:params:xml:ns:yang:controller:netconf:northbound:tcp">-->
+ <!--<type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:northbound">prefix:netconf-server-dispatcher</type>-->
+ <!--<name>netconf-mdsal-server-dispatcher</name>-->
+ <!--</dispatcher>-->
+ <!--</module>-->
+
</modules>
<services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
<capability>urn:opendaylight:params:xml:ns:yang:controller:netconf:mdsal:mapper?module=netconf-mdsal-mapper&revision=2015-01-14</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:netconf:mdsal:monitoring?module=netconf-mdsal-monitoring&revision=2015-02-18</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:netconf:northbound:ssh?module=netconf-northbound-ssh&revision=2015-01-14</capability>
+ <capability>urn:opendaylight:params:xml:ns:yang:controller:netconf:northbound:tcp?module=netconf-northbound-tcp&revision=2015-04-23</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:config:netconf:northbound:impl?module=netconf-northbound-impl&revision=2015-01-12</capability>
<capability>urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:scheduled?module=threadpool-impl-scheduled&revision=2013-12-01</capability>
</required-capabilities>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-util</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>threadpool-config-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netty-config-api</artifactId>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>config</id>
+ <goals>
+ <goal>generate-sources</goal>
+ </goals>
+ <configuration>
+ <codeGenerators>
+ <generator>
+ <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
+ <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
+ <additionalConfiguration>
+ <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
+ </additionalConfiguration>
+ </generator>
+ <generator>
+ <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
+ <outputBaseDir>${salGeneratorPath}</outputBaseDir>
+ </generator>
+ </codeGenerators>
+ <inspectDependencies>true</inspectDependencies>
+ </configuration>
+ </execution>
+ </executions>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>yang-jmx-generator-plugin</artifactId>
+ <version>${config.version}</version>
+ </dependency>
+ </dependencies>
+ </plugin>
</plugins>
</build>
--- /dev/null
+package org.opendaylight.controller.config.yang.netconf.northbound.tcp;
+
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.GenericFutureListener;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import org.opendaylight.controller.netconf.api.NetconfServerDispatcher;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class NetconfNorthboundTcpModule extends org.opendaylight.controller.config.yang.netconf.northbound.tcp.AbstractNetconfNorthboundTcpModule {
+
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfNorthboundTcpModule.class);
+
+ public NetconfNorthboundTcpModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+ super(identifier, dependencyResolver);
+ }
+
+ public NetconfNorthboundTcpModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.netconf.northbound.tcp.NetconfNorthboundTcpModule oldModule, java.lang.AutoCloseable oldInstance) {
+ super(identifier, dependencyResolver, oldModule, oldInstance);
+ }
+
+ @Override
+ public void customValidation() {
+ // add custom validation form module attributes here.
+ }
+
+ @Override
+ public java.lang.AutoCloseable createInstance() {
+ final NetconfServerDispatcher dispatch = getDispatcherDependency();
+ final ChannelFuture tcpServer = dispatch.createServer(getInetAddress());
+
+ tcpServer.addListener(new GenericFutureListener<ChannelFuture>() {
+ @Override
+ public void operationComplete(ChannelFuture future) throws Exception {
+ if (future.isDone() && future.isSuccess()) {
+ LOG.info("Netconf TCP endpoint started successfully at {}", getInetAddress());
+ } else {
+ LOG.warn("Unable to start TCP netconf server at {}", getInetAddress(), future.cause());
+ throw new RuntimeException("Unable to start TCP netconf server", future.cause());
+ }
+ }
+ });
+ return new NetconfServerCloseable(tcpServer);
+ }
+
+ private InetSocketAddress getInetAddress() {
+ try {
+ final InetAddress inetAd = InetAddress.getByName(getBindingAddress().getIpv4Address() == null ? getBindingAddress().getIpv6Address().getValue() : getBindingAddress().getIpv4Address().getValue());
+ return new InetSocketAddress(inetAd, getPort().getValue());
+ } catch (final UnknownHostException e) {
+ throw new IllegalArgumentException("Unable to bind netconf endpoint to address " + getBindingAddress(), e);
+ }
+ }
+
+ private static final class NetconfServerCloseable implements AutoCloseable {
+ private final ChannelFuture localServer;
+
+ public NetconfServerCloseable(final ChannelFuture localServer) {
+ this.localServer = localServer;
+ }
+
+ @Override
+ public void close() throws Exception {
+ if(localServer.isDone()) {
+ localServer.channel().close();
+ } else {
+ localServer.cancel(true);
+ }
+ }
+ }
+
+}
--- /dev/null
+/*
+* Generated file
+*
+* Generated from: yang module name: netconf-northbound-tcp yang module local name: netconf-northbound-tcp
+* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
+* Generated at: Thu Apr 23 16:34:55 CEST 2015
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.netconf.northbound.tcp;
+public class NetconfNorthboundTcpModuleFactory extends org.opendaylight.controller.config.yang.netconf.northbound.tcp.AbstractNetconfNorthboundTcpModuleFactory {
+
+}
--- /dev/null
+module netconf-northbound-tcp {
+ yang-version 1;
+ namespace "urn:opendaylight:params:xml:ns:yang:controller:netconf:northbound:tcp";
+ prefix "nni";
+
+ import netconf-northbound-mapper { prefix nnm; revision-date 2015-01-14; }
+ import netconf-northbound { prefix nn; revision-date 2015-01-14; }
+ import config { prefix config; revision-date 2013-04-05; }
+ import threadpool {prefix th;}
+ import netty {prefix netty;}
+ import ietf-inet-types { prefix inet; revision-date 2010-09-24; }
+
+ organization "Cisco Systems, Inc.";
+
+ description
+ "This module contains the base YANG definitions for
+ a default implementation of netconf northbound tcp server";
+
+ revision "2015-04-23" {
+ description
+ "Initial revision.";
+ }
+
+ identity netconf-northbound-tcp {
+ base config:module-type;
+ config:java-name-prefix NetconfNorthboundTcp;
+ }
+
+ augment "/config:modules/config:module/config:configuration" {
+ case netconf-northbound-tcp {
+ when "/config:modules/config:module/config:type = 'netconf-northbound-tcp'";
+
+ leaf port {
+ type inet:port-number;
+ default 2831;
+ }
+
+ leaf binding-address {
+ type inet:ip-address;
+ default "0.0.0.0";
+ }
+
+ container dispatcher {
+ uses config:service-ref {
+ refine type {
+ config:required-identity nn:netconf-server-dispatcher;
+ }
+ }
+ }
+ }
+ }
+
+}
\ No newline at end of file
private final List<NetconfMessage> preparedMessages;
private final NetconfDeviceCommunicator sessionListener;
private final List<Integer> editBatches;
+ private final int editAmount;
public AsyncExecutionStrategy(final Parameters params, final List<NetconfMessage> editConfigMsgs, final NetconfDeviceCommunicator sessionListener) {
this.params = params;
this.preparedMessages = editConfigMsgs;
this.sessionListener = sessionListener;
- this.editBatches = countEditBatchSizes(params);
+ this.editBatches = countEditBatchSizes(params, editConfigMsgs.size());
+ editAmount = editConfigMsgs.size();
}
- private static List<Integer> countEditBatchSizes(final Parameters params) {
+ private static List<Integer> countEditBatchSizes(final Parameters params, final int amount) {
final List<Integer> editBatches = Lists.newArrayList();
- if (params.editBatchSize != params.editCount) {
- final int fullBatches = params.editCount / params.editBatchSize;
+ if (params.editBatchSize != amount) {
+ final int fullBatches = amount / params.editBatchSize;
for (int i = 0; i < fullBatches; i++) {
editBatches.add(params.editBatchSize);
}
- if (params.editCount % params.editBatchSize != 0) {
- editBatches.add(params.editCount % params.editBatchSize);
+ if (amount % params.editBatchSize != 0) {
+ editBatches.add(amount % params.editBatchSize);
}
} else {
editBatches.add(params.editBatchSize);
}
}
- Preconditions.checkState(responseCounter.get() == params.editCount + editBatches.size(), "Not all responses were received, only %s from %s", responseCounter.get(), params.editCount + editBatches.size());
+ Preconditions.checkState(responseCounter.get() == editAmount + editBatches.size(), "Not all responses were received, only %s from %s", responseCounter.get(), params.editCount + editBatches.size());
}
}
@Arg(dest = "msg-timeout")
public long msgTimeout;
+ @Arg(dest = "tcp-header")
+ public String tcpHeader;
+
+ @Arg(dest = "thread-amount")
+ public int threadAmount;
+
static ArgumentParser getParser() {
final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf stress client");
.setDefault(false)
.dest("ssh");
+ parser.addArgument("--tcp-header")
+ .type(String.class)
+ .required(false)
+ .dest("tcp-header");
+
+ parser.addArgument("--thread-amount")
+ .type(Integer.class)
+ .setDefault(1)
+ .dest("thread-amount");
+
// TODO add get-config option instead of edit + commit
// TODO different edit config content
import ch.qos.logback.classic.Level;
import com.google.common.base.Charsets;
import com.google.common.base.Stopwatch;
-import com.google.common.collect.Lists;
import com.google.common.io.Files;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
-import io.netty.util.concurrent.GlobalEventExecutor;
import java.io.IOException;
-import java.net.InetSocketAddress;
+import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
-import org.opendaylight.controller.netconf.client.NetconfClientSession;
-import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
-import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.api.RemoteDevice;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
-import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
-import org.opendaylight.protocol.framework.NeverReconnectStrategy;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.CommitInput;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.EditConfigInput;
import org.opendaylight.yangtools.yang.common.QName;
" <target>\n" +
" <candidate/>\n" +
" </target>\n" +
+ " <default-operation>none</default-operation>" +
" <config/>\n" +
" </edit-config>\n" +
"</rpc>");
}
}
- private static final String MSG_ID_PLACEHOLDER = "{MSG_ID}";
private static final String MSG_ID_PLACEHOLDER_REGEX = "\\{MSG_ID\\}";
+ private static final String PHYS_ADDR_PLACEHOLDER = "{PHYS_ADDR}";
+
+ private static long macStart = 0xAABBCCDD0000L;
public static void main(final String[] args) {
final Parameters params = parseArgs(args, Parameters.getParser());
params.validate();
- // TODO remove
- try {
- Thread.sleep(10000);
- } catch (final InterruptedException e) {
-// e.printStackTrace();
- }
-
final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
+ final int threadAmount = params.threadAmount;
+ LOG.info("thread amount: " + threadAmount);
+ final int requestsPerThread = params.editCount / params.threadAmount;
+ LOG.info("requestsPerThread: " + requestsPerThread);
+ final int leftoverRequests = params.editCount % params.threadAmount;
+ LOG.info("leftoverRequests: " + leftoverRequests);
+
+
LOG.info("Preparing messages");
// Prepare all msgs up front
- final List<NetconfMessage> preparedMessages = Lists.newArrayListWithCapacity(params.editCount);
+ final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
+ for (int i = 0; i < threadAmount; i++) {
+ if (i != threadAmount - 1) {
+ allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
+ } else {
+ allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
+ }
+ }
+
final String editContentString;
- boolean needsModification = false;
try {
editContentString = Files.toString(params.editContent, Charsets.UTF_8);
- if(editContentString.contains(MSG_ID_PLACEHOLDER)) {
- needsModification = true;
- };
- } catch (IOException e) {
+ } catch (final IOException e) {
throw new IllegalArgumentException("Cannot read content of " + params.editContent);
}
- for (int i = 0; i < params.editCount; i++) {
- final Document msg = XmlUtil.createDocumentCopy(editBlueprint);
- msg.getDocumentElement().setAttribute("message-id", Integer.toString(i));
- final NetconfMessage netconfMessage = new NetconfMessage(msg);
-
- final Element editContentElement;
- try {
- // Insert message id where needed
- final String specificEditContent = needsModification ?
- editContentString.replaceAll(MSG_ID_PLACEHOLDER_REGEX, Integer.toString(i)) :
- editContentString;
-
- editContentElement = XmlUtil.readXmlToElement(specificEditContent);
- final Node config = ((Element) msg.getDocumentElement().getElementsByTagName("edit-config").item(0)).
- getElementsByTagName("config").item(0);
- config.appendChild(msg.importNode(editContentElement, true));
- } catch (final IOException | SAXException e) {
- throw new IllegalArgumentException("Edit content file is unreadable", e);
+ for (int i = 0; i < threadAmount; i++) {
+ final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
+ int padding = 0;
+ if (i == threadAmount - 1) {
+ padding = leftoverRequests;
+ }
+ for (int j = 0; j < requestsPerThread + padding; j++) {
+ LOG.debug("id: " + (i * requestsPerThread + j));
+ preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
}
-
- preparedMessages.add(netconfMessage);
-
}
-
final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
final Timer timer = new HashedWheelTimer();
final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer);
- final NetconfDeviceCommunicator sessionListener = getSessionListener(params.getInetAddress());
+ final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
+ for (final List<NetconfMessage> messages : allPreparedMessages) {
+ callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
+ }
- final NetconfClientConfiguration cfg = getNetconfClientConfiguration(params, sessionListener);
+ final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);
- LOG.info("Connecting to netconf server {}:{}", params.ip, params.port);
- final NetconfClientSession netconfClientSession;
+ LOG.info("Starting stress test");
+ final Stopwatch started = Stopwatch.createStarted();
try {
- netconfClientSession = netconfClientDispatcher.createClient(cfg).get();
+ final List<Future<Boolean>> futures = executorService.invokeAll(callables);
+ for (final Future<Boolean> future : futures) {
+ try {
+ future.get(4L, TimeUnit.MINUTES);
+ } catch (ExecutionException | TimeoutException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ executorService.shutdownNow();
} catch (final InterruptedException e) {
- throw new RuntimeException(e);
- } catch (final ExecutionException e) {
- throw new RuntimeException("Unable to connect", e);
+ throw new RuntimeException("Unable to execute requests", e);
}
-
- LOG.info("Starting stress test");
- final Stopwatch started = Stopwatch.createStarted();
- getExecutionStrategy(params, preparedMessages, sessionListener).invoke();
started.stop();
LOG.info("FINISHED. Execution time: {}", started);
LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
// Cleanup
- netconfClientSession.close();
timer.stop();
try {
nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
}
}
- private static ExecutionStrategy getExecutionStrategy(final Parameters params, final List<NetconfMessage> preparedMessages, final NetconfDeviceCommunicator sessionListener) {
- if(params.async) {
- return new AsyncExecutionStrategy(params, preparedMessages, sessionListener);
- } else {
- return new SyncExecutionStrategy(params, preparedMessages, sessionListener);
+ static NetconfMessage prepareMessage(final int id, final String editContentString) {
+ final Document msg = XmlUtil.createDocumentCopy(editBlueprint);
+ msg.getDocumentElement().setAttribute("message-id", Integer.toString(id));
+ final NetconfMessage netconfMessage = new NetconfMessage(msg);
+
+ final Element editContentElement;
+ try {
+ // Insert message id where needed
+ String specificEditContent = editContentString.replaceAll(MSG_ID_PLACEHOLDER_REGEX, Integer.toString(id));
+
+ final StringBuilder stringBuilder = new StringBuilder(specificEditContent);
+ int idx = stringBuilder.indexOf(PHYS_ADDR_PLACEHOLDER);
+ while (idx!= -1) {
+ stringBuilder.replace(idx, idx + PHYS_ADDR_PLACEHOLDER.length(), getMac(macStart++));
+ idx = stringBuilder.indexOf(PHYS_ADDR_PLACEHOLDER);
+ }
+ specificEditContent = stringBuilder.toString();
+
+ editContentElement = XmlUtil.readXmlToElement(specificEditContent);
+ final Node config = ((Element) msg.getDocumentElement().getElementsByTagName("edit-config").item(0)).
+ getElementsByTagName("config").item(0);
+ config.appendChild(msg.importNode(editContentElement, true));
+ } catch (final IOException | SAXException e) {
+ throw new IllegalArgumentException("Edit content file is unreadable", e);
}
+
+ return netconfMessage;
}
private static NetconfClientDispatcherImpl configureClientDispatcher(final Parameters params, final NioEventLoopGroup nioGroup, final Timer timer) {
return netconfClientDispatcher;
}
- private static NetconfClientConfiguration getNetconfClientConfiguration(final Parameters params, final NetconfDeviceCommunicator sessionListener) {
- final NetconfClientConfigurationBuilder netconfClientConfigurationBuilder = NetconfClientConfigurationBuilder.create();
- netconfClientConfigurationBuilder.withSessionListener(sessionListener);
- netconfClientConfigurationBuilder.withAddress(params.getInetAddress());
- netconfClientConfigurationBuilder.withProtocol(params.ssh ? NetconfClientConfiguration.NetconfClientProtocol.SSH : NetconfClientConfiguration.NetconfClientProtocol.TCP);
- netconfClientConfigurationBuilder.withConnectionTimeoutMillis(20000L);
- netconfClientConfigurationBuilder.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
- return netconfClientConfigurationBuilder.build();
- }
+ public static String getMac(long mac) {
+ StringBuilder m = new StringBuilder(Long.toString(mac, 16));
+
+ for (int i = m.length(); i < 12; i++) {
+ m.insert(0, "0");
+ }
+
+ for (int j = m.length() - 2; j >= 2; j-=2) {
+ m.insert(j, ":");
+ }
- static NetconfDeviceCommunicator getSessionListener(final InetSocketAddress inetAddress) {
- final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> loggingRemoteDevice = new LoggingRemoteDevice();
- return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test", inetAddress), loggingRemoteDevice);
+ return m.toString();
}
private static Parameters parseArgs(final String[] args, final ArgumentParser parser) {
}
- private static class LoggingRemoteDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
+ static class LoggingRemoteDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
@Override
public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities, final NetconfDeviceCommunicator netconfDeviceCommunicator) {
LOG.info("Session established");
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.netconf.test.tool.client.stress;
+
+import io.netty.util.concurrent.GlobalEventExecutor;
+import java.net.InetSocketAddress;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
+import org.opendaylight.controller.netconf.client.NetconfClientSession;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
+import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
+import org.opendaylight.controller.sal.connect.api.RemoteDevice;
+import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
+import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
+import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.protocol.framework.NeverReconnectStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class StressClientCallable implements Callable<Boolean>{
+
+ private static final Logger LOG = LoggerFactory.getLogger(StressClientCallable.class);
+
+ private Parameters params;
+ private final NetconfDeviceCommunicator sessionListener;
+ private final NetconfClientDispatcherImpl netconfClientDispatcher;
+ private final NetconfClientConfiguration cfg;
+ private final NetconfClientSession netconfClientSession;
+ private final ExecutionStrategy executionStrategy;
+
+ public StressClientCallable(final Parameters params,
+ final NetconfClientDispatcherImpl netconfClientDispatcher,
+ final List<NetconfMessage> preparedMessages) {
+ this.params = params;
+ this.sessionListener = getSessionListener(params.getInetAddress());
+ this.netconfClientDispatcher = netconfClientDispatcher;
+ cfg = getNetconfClientConfiguration(this.params, this.sessionListener);
+
+ LOG.info("Connecting to netconf server {}:{}", params.ip, params.port);
+ try {
+ netconfClientSession = netconfClientDispatcher.createClient(cfg).get();
+ } catch (final InterruptedException e) {
+ throw new RuntimeException(e);
+ } catch (final ExecutionException e) {
+ throw new RuntimeException("Unable to connect", e);
+ }
+ executionStrategy = getExecutionStrategy(params, preparedMessages, sessionListener);
+ }
+
+ @Override
+ public Boolean call() throws Exception {
+ executionStrategy.invoke();
+ netconfClientSession.close();
+ return true;
+ }
+
+ private static ExecutionStrategy getExecutionStrategy(final Parameters params, final List<NetconfMessage> preparedMessages, final NetconfDeviceCommunicator sessionListener) {
+ if(params.async) {
+ return new AsyncExecutionStrategy(params, preparedMessages, sessionListener);
+ } else {
+ return new SyncExecutionStrategy(params, preparedMessages, sessionListener);
+ }
+ }
+
+ private static NetconfDeviceCommunicator getSessionListener(final InetSocketAddress inetAddress) {
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> loggingRemoteDevice = new StressClient.LoggingRemoteDevice();
+ return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test", inetAddress), loggingRemoteDevice);
+ }
+
+ private static NetconfClientConfiguration getNetconfClientConfiguration(final Parameters params, final NetconfDeviceCommunicator sessionListener) {
+ final NetconfClientConfigurationBuilder netconfClientConfigurationBuilder = NetconfClientConfigurationBuilder.create();
+ netconfClientConfigurationBuilder.withSessionListener(sessionListener);
+ netconfClientConfigurationBuilder.withAddress(params.getInetAddress());
+ if(params.tcpHeader != null) {
+ final String header = params.tcpHeader.replaceAll("\"", "").trim() + "\n";
+ netconfClientConfigurationBuilder.withAdditionalHeader(new NetconfHelloMessageAdditionalHeader(null, null, null, null, null) {
+ @Override
+ public String toFormattedString() {
+ LOG.debug("Sending TCP header {}", header);
+ return header;
+ }
+ });
+ }
+ netconfClientConfigurationBuilder.withProtocol(params.ssh ? NetconfClientConfiguration.NetconfClientProtocol.SSH : NetconfClientConfiguration.NetconfClientProtocol.TCP);
+ netconfClientConfigurationBuilder.withConnectionTimeoutMillis(20000L);
+ netconfClientConfigurationBuilder.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
+ return netconfClientConfigurationBuilder.build();
+ }
+}
private final List<NetconfMessage> preparedMessages;
private final NetconfDeviceCommunicator sessionListener;
private final List<Integer> editBatches;
+ private final int editAmount;
public SyncExecutionStrategy(final Parameters params, final List<NetconfMessage> preparedMessages, final NetconfDeviceCommunicator sessionListener) {
this.params = params;
this.preparedMessages = preparedMessages;
this.sessionListener = sessionListener;
- editBatches = countEditBatchSizes(params);
+ this.editBatches = countEditBatchSizes(params, preparedMessages.size());
+ editAmount = preparedMessages.size();
}
- private static List<Integer> countEditBatchSizes(final Parameters params) {
+ private static List<Integer> countEditBatchSizes(final Parameters params, final int amount) {
final List<Integer> editBatches = Lists.newArrayList();
- if (params.editBatchSize != params.editCount) {
- final int fullBatches = params.editCount / params.editBatchSize;
+ if (params.editBatchSize != amount) {
+ final int fullBatches = amount / params.editBatchSize;
for (int i = 0; i < fullBatches; i++) {
editBatches.add(params.editBatchSize);
}
- if (params.editCount % params.editBatchSize != 0) {
- editBatches.add(params.editCount % params.editBatchSize);
+ if (amount % params.editBatchSize != 0) {
+ editBatches.add(amount % params.editBatchSize);
}
} else {
editBatches.add(params.editBatchSize);
sessionListener.sendRequest(StressClient.COMMIT_MSG, StressClient.COMMIT_QNAME));
}
- Preconditions.checkState(responseCounter.get() == params.editCount + editBatches.size(), "Not all responses were received, only %s from %s", responseCounter.get(), params.editCount + editBatches.size());
+ Preconditions.checkState(responseCounter.get() == editAmount + editBatches.size(), "Not all responses were received, only %s from %s", responseCounter.get(), params.editCount + editBatches.size());
}
private void waitForResponse(AtomicInteger responseCounter, final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture) {