Merge "Bug 1773: Use new Binding Notification Broker by default." into stable/lithium
authorEd Warnicke <hagbard@gmail.com>
Tue, 5 May 2015 15:15:17 +0000 (15:15 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Tue, 5 May 2015 15:15:17 +0000 (15:15 +0000)
63 files changed:
features/mdsal/src/main/resources/features.xml
features/netconf-connector/src/main/resources/features.xml
opendaylight/commons/opendaylight/pom.xml
opendaylight/md-sal/messagebus-impl/src/main/java/org/opendaylight/controller/messagebus/app/impl/EventSourceTopology.java
opendaylight/md-sal/sal-binding-broker/pom.xml
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDOMRpcProviderServiceAdapter.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDOMRpcServiceAdapter.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingToNormalizedNodeCodec.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ContextReferenceExtractor.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/DirectGetterRouteContextExtractor.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/GetValueRouteContextExtractor.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/LazySerializedContainerNode.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/RpcServiceAdapter.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/ContextExtractorTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ConcurrentDOMDataBroker.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStore.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardSnapshotCohort.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransaction.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransactionChain.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransactionFactory.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxy.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionContextImpl.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionFutureCallback.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionProxy.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionType.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/compat/PreLithiumTransactionContextImpl.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/identifiers/ChainedTransactionIdentifier.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/identifiers/TransactionIdentifier.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/jmx/mbeans/shard/ShardStats.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/jmx/mbeans/shard/ShardStatsMXBean.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractTransactionProxyTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionFailureTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxyTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/compat/PreLithiumTransactionProxyTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/compat/ShardTransactionHeliumBackwardsCompatibilityTest.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RoutingTable.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistry.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/gossip/BucketStore.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/mbeans/RemoteRpcRegistryMXBean.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/mbeans/RemoteRpcRegistryMXBeanImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonNormalizedNodeBodyReader.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlNormalizedNodeBodyReader.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfProviderImpl.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/StatisticsRestconfServiceWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/yang/opendaylight-rest-connector.yang
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreService.java
opendaylight/netconf/netconf-mdsal-config/src/main/resources/initial/08-netconf-mdsal.xml
opendaylight/netconf/netconf-tcp/pom.xml
opendaylight/netconf/netconf-tcp/src/main/java/org/opendaylight/controller/config/yang/netconf/northbound/tcp/NetconfNorthboundTcpModule.java [new file with mode: 0644]
opendaylight/netconf/netconf-tcp/src/main/java/org/opendaylight/controller/config/yang/netconf/northbound/tcp/NetconfNorthboundTcpModuleFactory.java [new file with mode: 0644]
opendaylight/netconf/netconf-tcp/src/main/yang/netconf-northbound-tcp.yang [new file with mode: 0644]
opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/client/stress/AsyncExecutionStrategy.java
opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/client/stress/Parameters.java
opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/client/stress/StressClient.java
opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/client/stress/StressClientCallable.java [new file with mode: 0644]
opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/client/stress/SyncExecutionStrategy.java

index a992d2f95e19b497f81ae90641a269214095221c..cd45f09f124172d01eaac4d6153f9b055253710d 100644 (file)
@@ -27,6 +27,8 @@
     <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>
index 16af44f20808a66857120d1cdadef61cff53c371..96eb3e72494e3fdd99ddfb8726b988ca2fccee5a 100644 (file)
         <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>
index eca08dde82a3726bd32dd35d62a241214346076a..f7509e2aabbc9a3b52c1d310b0dd731154d3c729 100644 (file)
@@ -15,7 +15,7 @@
 
   <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>
index 10b9ec83cde9080a5eb652ea69b65936973b0f60..7771b82491f61f90207ac737742538bf370323d0 100644 (file)
@@ -78,10 +78,10 @@ public class EventSourceTopology implements EventAggregatorService, EventSourceR
                     .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;
@@ -205,12 +205,16 @@ public class EventSourceTopology implements EventAggregatorService, EventSourceR
     }
 
     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){
index b392eb240292351280ef2de81781d815835dc53e..bd67973b8c958d9fc1c0ddde20930fcefc0db8d6 100644 (file)
         <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>
index ba822989d81d8faa947db6885b9c002d46b3f054..05f11943cdb59391817eb1479823dfd01cb02984 100644 (file)
@@ -63,7 +63,7 @@ public class BindingDOMRpcProviderServiceAdapter {
     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;
     }
index 6b64b7ea55473a98027b75a7a96cf9571acfa00e..90d91458e1dcdf869dddd5f2c59d78e67bba71dc 100644 (file)
@@ -7,38 +7,21 @@
  */
 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>() {
 
@@ -78,45 +61,10 @@ public class BindingDOMRpcServiceAdapter implements RpcConsumerRegistry, Invocat
         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> {
index b727e5317b087cb7784cb83be78e596dc397698e..ec7df74e6098511885f595603c48afa6157adc3f 100644 (file)
@@ -10,6 +10,9 @@ package org.opendaylight.controller.md.sal.binding.impl;
 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;
@@ -46,20 +49,39 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 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);
     }
@@ -69,12 +91,26 @@ public class BindingToNormalizedNodeCodec implements BindingCodecTreeFactory, Bi
         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) {
@@ -219,6 +255,21 @@ public class BindingToNormalizedNodeCodec implements BindingCodecTreeFactory, Bi
         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) {
@@ -238,7 +289,8 @@ public class BindingToNormalizedNodeCodec implements BindingCodecTreeFactory, Bi
         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();
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ContextReferenceExtractor.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ContextReferenceExtractor.java
new file mode 100644 (file)
index 0000000..4653ca3
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * 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;
+    }
+
+
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/DirectGetterRouteContextExtractor.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/DirectGetterRouteContextExtractor.java
new file mode 100644 (file)
index 0000000..33e0582
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * 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);
+        }
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/GetValueRouteContextExtractor.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/GetValueRouteContextExtractor.java
new file mode 100644 (file)
index 0000000..d5d5a72
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * 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);
+        }
+    }
+
+
+}
index 9eb4ed76f6d15a44b3584e96c7043bf1ca2dce6b..332df7531d82e4a592dcf63ef1b1e5070c2547c9 100644 (file)
@@ -1,9 +1,9 @@
 /*
- * 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;
 
@@ -17,6 +17,9 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent
 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;
 
 /**
  *
@@ -31,21 +34,31 @@ class LazySerializedContainerNode implements ContainerNode {
     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;
         }
@@ -53,32 +66,59 @@ class LazySerializedContainerNode implements ContainerNode {
     }
 
     @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);
+        }
+    }
+
 }
index 61b32324a9d6b1c5db39e562c6a98f24e5e0e493..7f2a074af23db07a928a773a6f8e7ec1af2bb8fb 100644 (file)
@@ -1,40 +1,76 @@
 /*
- * 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() {
@@ -42,46 +78,131 @@ class RpcServiceAdapter implements InvocationHandler {
     }
 
     @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());
+        }
+
+    }
 }
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/ContextExtractorTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/ContextExtractorTest.java
new file mode 100644 (file)
index 0000000..a38f3f1
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * 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);
+    }
+ }
index b48e5946da46ecdc00b0a4c82dc5263ffcd13efc..aa5040fb11215711af2a511621d0831b8cd0c138 100644 (file)
@@ -9,18 +9,16 @@ package org.opendaylight.controller.cluster.datastore;
 
 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;
@@ -51,15 +49,9 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
     /**
      * 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);
     }
@@ -69,7 +61,7 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
     }
 
     @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.");
@@ -112,7 +104,7 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
                         doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
                     } else {
                         ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
-                        Futures.addCallback(canCommitFuture, this, internalFutureCallbackExecutor);
+                        Futures.addCallback(canCommitFuture, this, MoreExecutors.directExecutor());
                     }
                 }
             }
@@ -125,7 +117,7 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
         };
 
         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,
@@ -143,7 +135,7 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
                     doCommit(startTime, clientSubmitFuture, transaction, cohorts);
                 } else {
                     ListenableFuture<Void> preCommitFuture = cohortIterator.next().preCommit();
-                    Futures.addCallback(preCommitFuture, this, internalFutureCallbackExecutor);
+                    Futures.addCallback(preCommitFuture, this, MoreExecutors.directExecutor());
                 }
             }
 
@@ -155,7 +147,7 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
         };
 
         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,
@@ -175,7 +167,7 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
                     clientSubmitFuture.set();
                 } else {
                     ListenableFuture<Void> commitFuture = cohortIterator.next().commit();
-                    Futures.addCallback(commitFuture, this, internalFutureCallbackExecutor);
+                    Futures.addCallback(commitFuture, this, MoreExecutors.directExecutor());
                 }
             }
 
@@ -187,23 +179,23 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
         };
 
         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);
@@ -216,7 +208,7 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
         @SuppressWarnings("unchecked")
         ListenableFuture<Void>[] canCommitFutures = new ListenableFuture[cohorts.size()];
         int i = 0;
-        for(DOMStoreThreePhaseCommitCohort cohort: cohorts) {
+        for (DOMStoreThreePhaseCommitCohort cohort : cohorts) {
             canCommitFutures[i++] = cohort.abort();
         }
 
@@ -236,7 +228,7 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
                 // what's interesting to the client.
                 clientSubmitFuture.setException(clientException);
             }
-        }, internalFutureCallbackExecutor);
+        }, MoreExecutors.directExecutor());
     }
 
     /**
@@ -257,10 +249,10 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
          */
         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
@@ -321,41 +313,4 @@ public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
             }
         }
     }
-
-    /**
-     * 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;
-        }
-    }
 }
index 69c127f2897017f218222b2a95b270b1bcc9f0de..a136cc6f75392e9d95426fe786d10e9381a1a6cd 100644 (file)
@@ -149,19 +149,19 @@ public class DistributedDataStore implements DOMStore, SchemaContextListener,
 
     @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
index e62e918e5e7eff53b8f7e00dbe1e8300d270b59f..2fd51de8b674be89a065f28d5f2cacd16ec101fc 100644 (file)
@@ -493,7 +493,7 @@ public class Shard extends RaftActor {
             ShardTransactionIdentifier transactionId, String transactionChainId,
             short clientVersion ) {
 
-        return transactionActorFactory.newShardTransaction(TransactionProxy.TransactionType.fromInt(transactionType),
+        return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
                 transactionId, transactionChainId, clientVersion);
     }
 
index 600509a26b87b480156f4baf843f2b887ed4f655..c4ac727cb3b59fa3efa77b2ef3ccf7427c2a81a7 100644 (file)
@@ -51,7 +51,7 @@ class ShardSnapshotCohort implements RaftActorSnapshotCohort {
                 "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);
     }
index 600ec393971ffe72efd12dfaaaf472cc61edd204..4f59f9feb52a5da87310d8d5e442bd2ca4dcf6b8 100644 (file)
@@ -16,7 +16,6 @@ import akka.japi.Creator;
 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;
index 7a163088d4bec3938132285810ae35d70f2127fe..aedc6c42b862d0cc2ffd94fc9082b82d38f2aa2e 100644 (file)
@@ -13,7 +13,6 @@ import akka.actor.ActorRef;
 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;
index 3a92062e7f86972d55fe7f230c655898d0f0acfb..f8b8b9c95252834b2f0661a2658005124c53ef0f 100644 (file)
@@ -37,7 +37,7 @@ class ShardTransactionActorFactory {
         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) {
index cf261cbd2af103b70f3dfce9885903a88ee293e6..97f3e7444d3ee564c88845256e7448209036fe09 100644 (file)
@@ -91,20 +91,20 @@ public class TransactionChainProxy implements DOMStoreTransactionChain {
         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
@@ -115,7 +115,7 @@ public class TransactionChainProxy implements DOMStoreTransactionChain {
         actorContext.broadcast(new CloseTransactionChain(transactionChainId).toSerializable());
     }
 
-    private ChainedTransactionProxy allocateWriteTransaction(TransactionProxy.TransactionType type) {
+    private ChainedTransactionProxy allocateWriteTransaction(TransactionType type) {
         State localState = currentState;
 
         checkReadyState(localState);
index a9deeaaeba0806a1ad355dfeb40216d4a624219f..b6fe2c29bda9872245c90fa93f7aea7c4eeb6d5c 100644 (file)
@@ -30,7 +30,6 @@ import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
 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;
@@ -38,7 +37,6 @@ 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;
@@ -49,11 +47,10 @@ public class TransactionContextImpl extends AbstractTransactionContext {
     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;
@@ -142,7 +139,7 @@ public class TransactionContextImpl extends AbstractTransactionContext {
     }
 
     private BatchedModifications newBatchedModifications() {
-        return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, transactionChainId);
+        return new BatchedModifications(getIdentifier().toString(), remoteTransactionVersion, getIdentifier().getChainId());
     }
 
     private void batchModification(Modification modification) {
index a8a93c5e7ce196a2a5e7c0a0e60678b40bbb0854..0fddd66c54cbe77ece3f7d52a40f8a009c1e978c 100644 (file)
@@ -17,7 +17,6 @@ import java.util.List;
 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;
index e397ab501c064adf98c5ee6c2f6708f05eb6f2fe..5081c9b4f8f652e55e5241733051bc8064aa96e2 100644 (file)
@@ -62,23 +62,6 @@ import scala.concurrent.Promise;
  */
 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,
@@ -114,7 +97,6 @@ public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIde
 
     private final TransactionType transactionType;
     final ActorContext actorContext;
-    private final String transactionChainId;
     private final SchemaContext schemaContext;
     private TransactionState state = TransactionState.OPEN;
 
@@ -127,25 +109,24 @@ public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIde
     }
 
     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
@@ -381,7 +362,7 @@ public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIde
         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);
@@ -421,7 +402,7 @@ public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIde
         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;
@@ -521,7 +502,7 @@ public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIde
     }
 
     String getTransactionChainId() {
-        return transactionChainId;
+        return getIdentifier().getChainId();
     }
 
     protected ActorContext getActorContext() {
@@ -558,11 +539,11 @@ public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIde
 
         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);
         }
     }
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionType.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionType.java
new file mode 100644 (file)
index 0000000..649dae5
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * 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
index 8b6cce6c5bd392101a6e91040a08596ac743dfe5..249a115588b7b1f78dbd7e720c777a958f9b23b6 100644 (file)
@@ -20,7 +20,6 @@ import org.opendaylight.controller.cluster.datastore.messages.WriteData;
 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;
@@ -37,10 +36,9 @@ public class PreLithiumTransactionContextImpl extends TransactionContextImpl {
     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;
     }
 
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/identifiers/ChainedTransactionIdentifier.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/identifiers/ChainedTransactionIdentifier.java
new file mode 100644 (file)
index 0000000..1aec854
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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;
+    }
+}
index 32637a578e2d2af08c79f160bade7a9e2faf62aa..6742b5c7db259998da37767facea6482c06725dd 100644 (file)
@@ -9,6 +9,7 @@
 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-";
@@ -22,6 +23,18 @@ public class TransactionIdentifier {
         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) {
index e3c8ced878232f2a831d541f6bbb3b14b233327d..2e8d0931397592d646ae8280fb369d34851ed976 100644 (file)
@@ -25,10 +25,8 @@ import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftS
 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;
@@ -282,27 +280,6 @@ public class ShardStats extends AbstractMXBean implements ShardStatsMXBean {
         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
      */
index 12cea50e44cb744845d9243fb312e141b1e947db..8115f79f3da5cbe337a43f312f932ac42c8d0aab 100644 (file)
@@ -2,8 +2,6 @@ package org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard;
 
 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
@@ -60,14 +58,6 @@ public interface ShardStatsMXBean {
 
    boolean isSnapshotCaptureInitiated();
 
-   ThreadExecutorStats getDataStoreExecutorStats();
-
-   ThreadExecutorStats getNotificationMgrExecutorStats();
-
-   List<ListenerNotificationQueueStats> getCurrentNotificationMgrListenerQueueStats();
-
-   int getMaxNotificationMgrListenerQueueSize();
-
    void resetTransactionCounters();
 
    long getInMemoryJournalDataSize();
index a64a5802b8387102bdfac19e4535a440088ccf55..c22b7acd386cf3c5ecc66ab8dbbf2cc1d75f7e8f 100644 (file)
@@ -46,7 +46,6 @@ import org.mockito.Mock;
 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;
index 1ecf0971c10d3f0a429f3c56ea36d84eaa44befc..06d9f360aae23ab8edb0d99e5529ae6457e1d3b7 100644 (file)
@@ -365,7 +365,7 @@ public class ShardTest extends AbstractShardTest {
             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);
@@ -386,7 +386,7 @@ public class ShardTest extends AbstractShardTest {
             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"),
@@ -961,7 +961,7 @@ public class ShardTest extends AbstractShardTest {
 
             // 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);
index e45389f5f36fbd151a24ae9e4d5a02a4995a2772..15f61660643ea1f02e84055d42aad749d305983e 100644 (file)
@@ -17,7 +17,6 @@ import akka.testkit.TestActorRef;
 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;
index 23984ad973933666d41fb60c762e18517181ef1a..f20db19bd7ea137cd786c9fc30cdb23c7828d53a 100644 (file)
@@ -17,7 +17,6 @@ import org.junit.Test;
 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;
index 026b5490288c1bbdeb1ec44d37e998abddad813e..76f299b548596a05b11280c8c0402ea6c0faae7b 100644 (file)
@@ -21,8 +21,8 @@ import static org.mockito.Mockito.never;
 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;
index 844feb2f47e988b89498a80946d97aecbff8c049..dd55441c2a22a014d725674379c071c990c051cf 100644 (file)
@@ -11,9 +11,9 @@ import static org.mockito.Mockito.doReturn;
 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;
@@ -34,7 +34,6 @@ import org.junit.Assert;
 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;
@@ -677,7 +676,7 @@ public class TransactionProxyTest extends AbstractTransactionProxyTest {
     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);
index ca342b960a8749d78ae5aa0b1879b06ecc61110b..5681b760920a8615910bb1661ed16702b42df519 100644 (file)
@@ -15,8 +15,8 @@ import static org.mockito.Matchers.eq;
 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;
index e206e69cdaaa88d04ca38ab530865ba9e7e37320..cdbab1c6d1c7b9cdd70bddf92efc733ee64d7f93 100644 (file)
@@ -22,7 +22,7 @@ import org.opendaylight.controller.cluster.datastore.DatastoreContext;
 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;
@@ -73,7 +73,7 @@ public class ShardTransactionHeliumBackwardsCompatibilityTest extends AbstractAc
             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");
@@ -147,7 +147,7 @@ public class ShardTransactionHeliumBackwardsCompatibilityTest extends AbstractAc
             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");
index f12fda0aa11a91f93bfffd2d6eb002ec76fb7b5e..f3cb78a30148e0a0de638120cfb6f973c822bc0f 100644 (file)
@@ -75,7 +75,7 @@ public class RpcManager extends AbstractUntypedActor {
         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 =
index f67657f6927801931fae2fd0434481169f2f3de8..fa93a3b83f03153d4dd031ceda1f67bb6f3d4929 100644 (file)
@@ -13,6 +13,8 @@ import akka.japi.Pair;
 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;
 
@@ -41,6 +43,10 @@ public class RoutingTable implements Copier<RoutingTable>, Serializable {
         }
     }
 
+    public Set<RpcRouter.RouteIdentifier<?, ?, ?>> getRoutes() {
+        return table.keySet();
+    }
+
     public void addRoute(RpcRouter.RouteIdentifier<?,?,?> routeId){
         table.put(routeId, System.currentTimeMillis());
     }
index 219646d8478ade824d22589842c4d4ddf1edccaa..1dcc4e140595250a0414eba706eada3e776f4ece 100644 (file)
@@ -8,6 +8,8 @@
 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;
@@ -19,6 +21,8 @@ import org.opendaylight.controller.remote.rpc.registry.RpcRegistry.Messages.Remo
 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;
 
@@ -34,6 +38,10 @@ public class RpcRegistry extends BucketStore<RoutingTable> {
         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
@@ -220,4 +228,15 @@ public class RpcRegistry extends BucketStore<RoutingTable> {
             }
         }
     }
+
+    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;
+        }
+    }
 }
index 628deb4311cebe1da5ff1b44deb715d933b8b8b2..febff0bc92efc4c8ad896a92e3d367156c6fd345 100644 (file)
@@ -13,7 +13,6 @@ import akka.actor.ActorRefProvider;
 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;
@@ -230,7 +229,7 @@ public class BucketStore<T extends Copier<T>> extends AbstractUntypedActorWithMe
         }
     }
 
-    protected BucketImpl<T> getLocalBucket() {
+    public BucketImpl<T> getLocalBucket() {
         return localBucket;
     }
 
@@ -239,12 +238,11 @@ public class BucketStore<T extends Copier<T>> extends AbstractUntypedActorWithMe
         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;
     }
 }
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/mbeans/RemoteRpcRegistryMXBean.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/mbeans/RemoteRpcRegistryMXBean.java
new file mode 100644 (file)
index 0000000..ddd3333
--- /dev/null
@@ -0,0 +1,22 @@
+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);
+}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/mbeans/RemoteRpcRegistryMXBeanImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/mbeans/RemoteRpcRegistryMXBeanImpl.java
new file mode 100644 (file)
index 0000000..c7d9b99
--- /dev/null
@@ -0,0 +1,156 @@
+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
index 4d8463adae66cb1e53ba06b2014b0bc8702fc4b4..3be247a3bbdc71a911570d431dc679c86e1222d4 100644 (file)
@@ -104,6 +104,8 @@ public class JsonNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPr
                 result = partialResult;
             }
             return new NormalizedNodeContext(path,result);
+        } catch (final RestconfDocumentedException e) {
+            throw e;
         } catch (final Exception e) {
             LOG.debug("Error parsing json input", e);
 
index 74a9bd2d313618be1b090e49c472bd7894457c50..2a9c5bf190cbed62c4756940942436ac8f88682e 100644 (file)
@@ -104,6 +104,8 @@ public class XmlNormalizedNodeBodyReader extends AbstractIdentifierAwareJaxRsPro
 
             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);
 
index 2da58a38203de35102e0cc5e7e667ec83adedeec..6cc62e859c9bade70e4125d2fea72a8addc6f875 100644 (file)
@@ -153,6 +153,11 @@ public class ControllerContext implements SchemaContextListener {
 
         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);
 
index 1514a15d1132417849a0efb29e53b0ea26113b8f..5e9ab7b9d0a0b818a577ddbcec502f10e6196bca 100644 (file)
@@ -417,18 +417,13 @@ public class RestconfImpl implements RestconfService {
                 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();
                 }
@@ -444,6 +439,9 @@ public class RestconfImpl implements RestconfService {
                 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);
         }
     }
 
index 84b092e10eae92f9fc7715162c6bbdc48a975ad1..624d709c60a7abd761c7c40011ffb0619cd66e4c 100644 (file)
@@ -11,6 +11,7 @@ import java.math.BigInteger;
 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;
@@ -78,15 +79,31 @@ public class RestconfProviderImpl implements Provider, AutoCloseable, RestConnec
     @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;
     }
 
@@ -96,6 +113,8 @@ public class RestconfProviderImpl implements Provider, AutoCloseable, RestConnec
         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;
     }
@@ -105,6 +124,6 @@ public class RestconfProviderImpl implements Provider, AutoCloseable, RestConnec
         final BigInteger rpcInvoke = stats.getRpc();
         final Rpcs rpcs = new Rpcs();
         rpcs.setReceivedRequests(rpcInvoke);
-        return rpcs ;
+        return rpcs;
     }
-}
+}
\ No newline at end of file
index 07178f537999ce0a04c285431c1398f684453e67..f4a5fbc926479c94ed3eaa762722483424036133 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.controller.sal.restconf.impl;
 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;
 
@@ -21,6 +22,16 @@ public class StatisticsRestconfServiceWrapper implements 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());
 
@@ -79,36 +90,115 @@ public class StatisticsRestconfServiceWrapper implements RestconfService {
     @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
@@ -144,4 +234,44 @@ public class StatisticsRestconfServiceWrapper implements RestconfService {
     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
index 6d2add6ff14313b8824a5ade4d8cba187260bc24..6fa9c86ec1879985afa664783f65e483ffad60da 100644 (file)
@@ -31,6 +31,14 @@ module opendaylight-rest-connector {
         leaf received-requests {
            type uint64;
         }
+
+        leaf successful-responses {
+            type uint64;
+        }
+
+        leaf failed-responses {
+            type uint64;
+        }
     }
 
     augment "/config:modules/config:module/config:configuration" {
@@ -70,6 +78,10 @@ module opendaylight-rest-connector {
                 container put {
                     uses statistics;
                 }
+                
+                container delete {
+                    uses statistics;
+                }
             }
 
             container operational {
index 29616620920111b394dbe450284a9443b362c8ac..ac3873e6b89be414429773ee54ee53b05bec4f2c 100644 (file)
@@ -137,15 +137,15 @@ public class YangStoreService implements YangStoreContext {
     }
 
     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
index 1982615173ec2aa7d36a39b7eb0733f759d55299..72a3dcf3885165aad54083ad4774d62e4fe29f8d 100644 (file)
               <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&amp;revision=2015-01-14</capability>
       <capability>urn:opendaylight:params:xml:ns:yang:controller:netconf:mdsal:monitoring?module=netconf-mdsal-monitoring&amp;revision=2015-02-18</capability>
       <capability>urn:opendaylight:params:xml:ns:yang:controller:netconf:northbound:ssh?module=netconf-northbound-ssh&amp;revision=2015-01-14</capability>
+      <capability>urn:opendaylight:params:xml:ns:yang:controller:netconf:northbound:tcp?module=netconf-northbound-tcp&amp;revision=2015-04-23</capability>
       <capability>urn:opendaylight:params:xml:ns:yang:controller:config:netconf:northbound:impl?module=netconf-northbound-impl&amp;revision=2015-01-12</capability>
       <capability>urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:scheduled?module=threadpool-impl-scheduled&amp;revision=2013-12-01</capability>
   </required-capabilities>
index 0a3ea5485dd1e74ed84b4f28a6d11536691e4f16..d83664367164fcd8330212ddc610cec8b993aa78 100644 (file)
       <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>
 
diff --git a/opendaylight/netconf/netconf-tcp/src/main/java/org/opendaylight/controller/config/yang/netconf/northbound/tcp/NetconfNorthboundTcpModule.java b/opendaylight/netconf/netconf-tcp/src/main/java/org/opendaylight/controller/config/yang/netconf/northbound/tcp/NetconfNorthboundTcpModule.java
new file mode 100644 (file)
index 0000000..903f413
--- /dev/null
@@ -0,0 +1,74 @@
+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);
+            }
+        }
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-tcp/src/main/java/org/opendaylight/controller/config/yang/netconf/northbound/tcp/NetconfNorthboundTcpModuleFactory.java b/opendaylight/netconf/netconf-tcp/src/main/java/org/opendaylight/controller/config/yang/netconf/northbound/tcp/NetconfNorthboundTcpModuleFactory.java
new file mode 100644 (file)
index 0000000..081486e
--- /dev/null
@@ -0,0 +1,13 @@
+/*
+* 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 {
+
+}
diff --git a/opendaylight/netconf/netconf-tcp/src/main/yang/netconf-northbound-tcp.yang b/opendaylight/netconf/netconf-tcp/src/main/yang/netconf-northbound-tcp.yang
new file mode 100644 (file)
index 0000000..a42fcad
--- /dev/null
@@ -0,0 +1,53 @@
+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
index 7b60a17827dfe388b3775c83800bac803f1ddc7a..af352b1c2e8e28d1b338c7fab9377d72860c97e7 100644 (file)
@@ -30,24 +30,26 @@ class AsyncExecutionStrategy implements ExecutionStrategy {
     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);
@@ -96,6 +98,6 @@ class AsyncExecutionStrategy implements ExecutionStrategy {
             }
         }
 
-        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());
     }
 }
index 6648bd4b5293510f5a40008a82d8d51c332828b4..8a9a915a08d4ef4a62c5d9a5326a78f20b758873 100644 (file)
@@ -52,6 +52,12 @@ public class Parameters {
     @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");
 
@@ -122,6 +128,16 @@ public class Parameters {
                 .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
 
index fe0a0bcd523a8249e45a9c9f66f687e72611e97c..2916ec52f7bed25d4d0065579db166b73c94b4c8 100644 (file)
@@ -11,31 +11,27 @@ package org.opendaylight.controller.netconf.test.tool.client.stress;
 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;
@@ -74,6 +70,7 @@ public final class StressClient {
                             "        <target>\n" +
                             "            <candidate/>\n" +
                             "        </target>\n" +
+                            "        <default-operation>none</default-operation>" +
                             "        <config/>\n" +
                             "    </edit-config>\n" +
                             "</rpc>");
@@ -82,92 +79,90 @@ public final class StressClient {
         }
     }
 
-    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);
@@ -176,12 +171,33 @@ public final class StressClient {
         }
     }
 
-    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) {
@@ -202,19 +218,18 @@ public final class StressClient {
         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) {
@@ -231,7 +246,7 @@ public final class StressClient {
     }
 
 
-    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");
diff --git a/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/client/stress/StressClientCallable.java b/opendaylight/netconf/netconf-testtool/src/main/java/org/opendaylight/controller/netconf/test/tool/client/stress/StressClientCallable.java
new file mode 100644 (file)
index 0000000..a4c5c57
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * 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();
+    }
+}
index 34142a7f2a49d89a47d3529b9fe976c5e76743fb..40f39022e6b41e9424f46421cc38c2e5837ceff2 100644 (file)
@@ -31,24 +31,26 @@ class SyncExecutionStrategy implements ExecutionStrategy {
     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);
@@ -82,7 +84,7 @@ class SyncExecutionStrategy implements ExecutionStrategy {
                     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) {