maven-eclipse.xml
.DS_STORE
.metadata
+opendaylight/md-sal/sal-distributed-datastore/journal
+
<bundle>mvn:org.opendaylight.controller/threadpool-config-api/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/threadpool-config-impl/${project.version}</bundle>
<feature version='${project.version}'>odl-config-startup</feature>
+ <configfile finalname="configuration/initial/00-netty.xml">mvn:org.opendaylight.controller/config-netty-config/${config.version}/xml/config</configfile>
</feature>
</features>
\ No newline at end of file
<bundle>mvn:org.opendaylight.controller/hosttracker/${hosttracker.api.version}</bundle>
<bundle>mvn:org.opendaylight.controller/hosttracker.implementation/${hosttracker.implementation.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/hosttracker.shell/${hosttracker.shell.version}</bundle>
<bundle>mvn:org.opendaylight.controller/forwarding.staticrouting</bundle>
<hosttracker.api.version>0.5.2-SNAPSHOT</hosttracker.api.version>
<hosttracker.implementation.version>0.5.2-SNAPSHOT</hosttracker.implementation.version>
<hosttracker.northbound.version>0.4.2-SNAPSHOT</hosttracker.northbound.version>
+ <hosttracker.shell.version>1.0.0-SNAPSHOT</hosttracker.shell.version>
<hosttracker_new.api.version>0.4.2-SNAPSHOT</hosttracker_new.api.version>
<hosttracker_new.implementation.version>0.4.2-SNAPSHOT</hosttracker_new.implementation.version>
<httpservice-bridge.northbound.version>0.0.2-SNAPSHOT</httpservice-bridge.northbound.version>
<artifactId>sal-rest-connector-config</artifactId>
<version>${mdsal.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-netty-config</artifactId>
+ <version>${config.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>md-sal-config</artifactId>
+ <version>${mdsal.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-config</artifactId>
+ <version>${netconf.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-connector-config</artifactId>
+ <version>${netconf.version}</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-rest-docgen</artifactId>
<artifactId>sample-toaster-provider</artifactId>
<version>${mdsal.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>toaster-config</artifactId>
+ <version>${mdsal.version}</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller.thirdparty</groupId>
<artifactId>com.sun.jersey.jersey-servlet</artifactId>
<artifactId>netty-event-executor-config</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
*/
package org.opendaylight.protocol.framework;
+import java.io.Closeable;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.google.common.base.Preconditions;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
-import io.netty.channel.Channel;
import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
-import java.io.Closeable;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
/**
* Dispatcher class for creating servers and clients. The idea is to first create servers and clients and the run the
* start method that will handle sockets in different thread.
*/
protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final PipelineInitializer<S> initializer) {
final Bootstrap b = new Bootstrap();
- final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<S>(executor, address, strategy, b);
+ final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, b);
b.option(ChannelOption.SO_KEEPALIVE, true).handler(
new ChannelInitializer<SocketChannel>() {
@Override
});
customizeBootstrap(b);
+ setWorkerGroup(b);
+ setChannelFactory(b);
+
+ p.connect();
+ LOG.debug("Client created.");
+ return p;
+ }
+ private void setWorkerGroup(final Bootstrap b) {
if (b.group() == null) {
b.group(workerGroup);
}
+ }
- // There is no way to detect if this was already set by
- // customizeBootstrap()
- try {
- b.channel(NioSocketChannel.class);
- } catch (IllegalStateException e) {
- LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
- }
+ /**
+ * Create a client but use a pre-configured bootstrap.
+ * This method however replaces the ChannelInitializer in the bootstrap. All other configuration is preserved.
+ *
+ * @param address remote address
+ */
+ protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final Bootstrap bootstrap, final PipelineInitializer<S> initializer) {
+ final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, bootstrap);
+
+ bootstrap.handler(
+ new ChannelInitializer<SocketChannel>() {
+ @Override
+ protected void initChannel(final SocketChannel ch) {
+ initializer.initializeChannel(ch, p);
+ }
+ });
p.connect();
LOG.debug("Client created.");
}
/**
+ *
+ * @deprecated use {@link org.opendaylight.protocol.framework.AbstractDispatcher#createReconnectingClient(java.net.InetSocketAddress, ReconnectStrategyFactory, org.opendaylight.protocol.framework.AbstractDispatcher.PipelineInitializer)} with only one reconnectStrategyFactory instead.
+ *
* Creates a client.
*
* @param address remote address
* @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
* success if it indicates no further attempts should be made and failure if it reports an error
*/
+ @Deprecated
protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
final ReconnectStrategy reestablishStrategy, final PipelineInitializer<S> initializer) {
+ return createReconnectingClient(address, connectStrategyFactory, initializer);
+ }
- final ReconnectPromise<S, L> p = new ReconnectPromise<S, L>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, reestablishStrategy, initializer);
- p.connect();
+ /**
+ * Creates a reconnecting client.
+ *
+ * @param address remote address
+ * @param connectStrategyFactory Factory for creating reconnection strategy for every reconnect attempt
+ *
+ * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
+ * success if it indicates no further attempts should be made and failure if it reports an error
+ */
+ protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
+ final PipelineInitializer<S> initializer) {
+ final Bootstrap b = new Bootstrap();
+
+ final ReconnectPromise<S, L> p = new ReconnectPromise<>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, b, initializer);
+
+ b.option(ChannelOption.SO_KEEPALIVE, true);
+ customizeBootstrap(b);
+ setWorkerGroup(b);
+ setChannelFactory(b);
+
+ p.connect();
return p;
}
+ private void setChannelFactory(final Bootstrap b) {
+ // There is no way to detect if this was already set by
+ // customizeBootstrap()
+ try {
+ b.channel(NioSocketChannel.class);
+ } catch (final IllegalStateException e) {
+ LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
+ }
+ }
+
/**
* @deprecated Should only be used with {@link AbstractDispatcher#AbstractDispatcher()}
*/
this.bossGroup.shutdownGracefully();
}
}
-
}
*/
package org.opendaylight.protocol.framework;
+import com.google.common.base.Preconditions;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.Promise;
-
import java.net.InetSocketAddress;
-
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Preconditions;
-
@ThreadSafe
final class ProtocolSessionPromise<S extends ProtocolSession<?>> extends DefaultPromise<S> {
private static final Logger LOG = LoggerFactory.getLogger(ProtocolSessionPromise.class);
LOG.debug("Promise {} attempting connect for {}ms", lock, timeout);
this.b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
- this.pending = this.b.connect(this.address).addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(final ChannelFuture cf) throws Exception {
- synchronized (lock) {
-
- LOG.debug("Promise {} connection resolved", lock);
-
- // Triggered when a connection attempt is resolved.
- Preconditions.checkState(ProtocolSessionPromise.this.pending.equals(cf));
-
- /*
- * The promise we gave out could have been cancelled,
- * which cascades to the connect getting cancelled,
- * but there is a slight race window, where the connect
- * is already resolved, but the listener has not yet
- * been notified -- cancellation at that point won't
- * stop the notification arriving, so we have to close
- * the race here.
- */
- if (isCancelled()) {
- if (cf.isSuccess()) {
- LOG.debug("Closing channel for cancelled promise {}", lock);
- cf.channel().close();
- }
- return;
- }
-
- if (!cf.isSuccess()) {
- LOG.debug("Attempt to connect to {} failed", ProtocolSessionPromise.this.address, cf.cause());
-
- final Future<Void> rf = ProtocolSessionPromise.this.strategy.scheduleReconnect(cf.cause());
- rf.addListener(new FutureListener<Void>() {
- @Override
- public void operationComplete(final Future<Void> sf) {
- synchronized (lock) {
- // Triggered when a connection attempt is to be made.
- Preconditions.checkState(ProtocolSessionPromise.this.pending.equals(sf));
-
- /*
- * The promise we gave out could have been cancelled,
- * which cascades to the reconnect attempt getting
- * cancelled, but there is a slight race window, where
- * the reconnect attempt is already enqueued, but the
- * listener has not yet been notified -- if cancellation
- * happens at that point, we need to catch it here.
- */
- if (!isCancelled()) {
- if (sf.isSuccess()) {
- connect();
- } else {
- setFailure(sf.cause());
- }
- }
- }
- }
- });
-
- ProtocolSessionPromise.this.pending = rf;
- } else {
- LOG.debug("Promise {} connection successful", lock);
- }
- }
- }
- });
+ final ChannelFuture connectFuture = this.b.connect(this.address);
+ // Add listener that attempts reconnect by invoking this method again.
+ connectFuture.addListener(new BootstrapConnectListener(lock));
+ this.pending = connectFuture;
} catch (final Exception e) {
- LOG.info("Failed to connect to {}", e);
+ LOG.info("Failed to connect to {}", address, e);
setFailure(e);
}
}
this.strategy.reconnectSuccessful();
return super.setSuccess(result);
}
+
+ private class BootstrapConnectListener implements ChannelFutureListener {
+ private final Object lock;
+
+ public BootstrapConnectListener(final Object lock) {
+ this.lock = lock;
+ }
+
+ @Override
+ public void operationComplete(final ChannelFuture cf) throws Exception {
+ synchronized (lock) {
+
+ LOG.debug("Promise {} connection resolved", lock);
+
+ // Triggered when a connection attempt is resolved.
+ Preconditions.checkState(ProtocolSessionPromise.this.pending.equals(cf));
+
+ /*
+ * The promise we gave out could have been cancelled,
+ * which cascades to the connect getting cancelled,
+ * but there is a slight race window, where the connect
+ * is already resolved, but the listener has not yet
+ * been notified -- cancellation at that point won't
+ * stop the notification arriving, so we have to close
+ * the race here.
+ */
+ if (isCancelled()) {
+ if (cf.isSuccess()) {
+ LOG.debug("Closing channel for cancelled promise {}", lock);
+ cf.channel().close();
+ }
+ return;
+ }
+
+ if(cf.isSuccess()) {
+ LOG.debug("Promise {} connection successful", lock);
+ return;
+ }
+
+ LOG.debug("Attempt to connect to {} failed", ProtocolSessionPromise.this.address, cf.cause());
+
+ final Future<Void> rf = ProtocolSessionPromise.this.strategy.scheduleReconnect(cf.cause());
+ rf.addListener(new ReconnectingStrategyListener());
+ ProtocolSessionPromise.this.pending = rf;
+ }
+ }
+
+ private class ReconnectingStrategyListener implements FutureListener<Void> {
+ @Override
+ public void operationComplete(final Future<Void> sf) {
+ synchronized (lock) {
+ // Triggered when a connection attempt is to be made.
+ Preconditions.checkState(ProtocolSessionPromise.this.pending.equals(sf));
+
+ /*
+ * The promise we gave out could have been cancelled,
+ * which cascades to the reconnect attempt getting
+ * cancelled, but there is a slight race window, where
+ * the reconnect attempt is already enqueued, but the
+ * listener has not yet been notified -- if cancellation
+ * happens at that point, we need to catch it here.
+ */
+ if (!isCancelled()) {
+ if (sf.isSuccess()) {
+ connect();
+ } else {
+ setFailure(sf.cause());
+ }
+ }
+ }
+ }
+ }
+
+ }
+
}
*/
package org.opendaylight.protocol.framework;
-import io.netty.channel.ChannelFuture;
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.Promise;
-
-import java.io.Closeable;
import java.net.InetSocketAddress;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.opendaylight.protocol.framework.AbstractDispatcher.PipelineInitializer;
-
-import com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
final class ReconnectPromise<S extends ProtocolSession<?>, L extends SessionListener<?, ?, ?>> extends DefaultPromise<Void> {
+ private static final Logger LOG = LoggerFactory.getLogger(ReconnectPromise.class);
+
private final AbstractDispatcher<S, L> dispatcher;
private final InetSocketAddress address;
private final ReconnectStrategyFactory strategyFactory;
- private final ReconnectStrategy strategy;
- private final PipelineInitializer<S> initializer;
+ private final Bootstrap b;
+ private final AbstractDispatcher.PipelineInitializer<S> initializer;
private Future<?> pending;
- private final AtomicBoolean negotiationFinished = new AtomicBoolean(false);
-
public ReconnectPromise(final EventExecutor executor, final AbstractDispatcher<S, L> dispatcher, final InetSocketAddress address,
- final ReconnectStrategyFactory connectStrategyFactory, final ReconnectStrategy reestablishStrategy,
- final PipelineInitializer<S> initializer) {
+ final ReconnectStrategyFactory connectStrategyFactory, final Bootstrap b, final AbstractDispatcher.PipelineInitializer<S> initializer) {
super(executor);
+ this.b = b;
+ this.initializer = Preconditions.checkNotNull(initializer);
this.dispatcher = Preconditions.checkNotNull(dispatcher);
this.address = Preconditions.checkNotNull(address);
this.strategyFactory = Preconditions.checkNotNull(connectStrategyFactory);
- this.strategy = Preconditions.checkNotNull(reestablishStrategy);
- this.initializer = Preconditions.checkNotNull(initializer);
}
- // FIXME: BUG-190: refactor
-
synchronized void connect() {
- negotiationFinished.set(false);
-
final ReconnectStrategy cs = this.strategyFactory.createReconnectStrategy();
- final ReconnectStrategy rs = new ReconnectStrategy() {
- @Override
- public Future<Void> scheduleReconnect(final Throwable cause) {
- return cs.scheduleReconnect(cause);
- }
- @Override
- public void reconnectSuccessful() {
- cs.reconnectSuccessful();
- }
-
- @Override
- public int getConnectTimeout() throws Exception {
- final int cst = cs.getConnectTimeout();
- final int rst = ReconnectPromise.this.strategy.getConnectTimeout();
-
- if (cst == 0) {
- return rst;
- }
- if (rst == 0) {
- return cst;
- }
- return Math.min(cst, rst);
- }
- };
-
- final Future<S> cf = this.dispatcher.createClient(this.address, rs, new PipelineInitializer<S>() {
+ // Set up a client with pre-configured bootstrap, but add a closed channel handler into the pipeline to support reconnect attempts
+ pending = this.dispatcher.createClient(this.address, cs, b, new AbstractDispatcher.PipelineInitializer<S>() {
@Override
public void initializeChannel(final SocketChannel channel, final Promise<S> promise) {
- addChannelClosedListener(channel.closeFuture());
initializer.initializeChannel(channel, promise);
+
+ // add closed channel handler
+ channel.pipeline().addFirst(new ClosedChannelHandler(ReconnectPromise.this));
}
});
+ }
- final Object lock = this;
- this.pending = cf;
+ /**
+ *
+ * @return true if initial connection was established successfully, false if initial connection failed due to e.g. Connection refused, Negotiation failed
+ */
+ private boolean isInitialConnectFinished() {
+ Preconditions.checkNotNull(pending);
+ return pending.isDone() && pending.isSuccess();
+ }
- cf.addListener(new FutureListener<S>() {
+ @Override
+ public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
+ if (super.cancel(mayInterruptIfRunning)) {
+ Preconditions.checkNotNull(pending);
+ this.pending.cancel(mayInterruptIfRunning);
+ return true;
+ }
- @Override
- public void operationComplete(final Future<S> future) {
- synchronized (lock) {
- if (!future.isSuccess()) {
- final Future<Void> rf = ReconnectPromise.this.strategy.scheduleReconnect(cf.cause());
-
- if(rf == null) {
- // This should reflect: no more reconnecting strategies, enough
- // Currently all reconnect strategies fail with exception, should return null
- return;
- }
-
- ReconnectPromise.this.pending = rf;
-
- rf.addListener(new FutureListener<Void>() {
- @Override
- public void operationComplete(final Future<Void> sf) {
- synchronized (lock) {
- /*
- * The promise we gave out could have been cancelled,
- * which cascades to the reconnect attempt getting
- * cancelled, but there is a slight race window, where
- * the reconnect attempt is already enqueued, but the
- * listener has not yet been notified -- if cancellation
- * happens at that point, we need to catch it here.
- */
- if (!isCancelled()) {
- if (sf.isSuccess()) {
- connect();
- } else {
- setFailure(sf.cause());
- }
- }
- }
- }
- });
- } else {
- /*
- * FIXME: BUG-190: we have a slight race window with cancellation
- * here. Analyze and define its semantics.
- */
- ReconnectPromise.this.strategy.reconnectSuccessful();
- negotiationFinished.set(true);
- }
- }
- }
- });
+ return false;
}
- private final ClosedChannelListener closedChannelListener = new ClosedChannelListener();
-
- class ClosedChannelListener implements Closeable, FutureListener<Void> {
+ /**
+ * Channel handler that responds to channelInactive event and reconnects the session.
+ * Only if the initial connection was successfully established and promise was not canceled.
+ */
+ private static final class ClosedChannelHandler extends ChannelInboundHandlerAdapter {
+ private final ReconnectPromise<?, ?> promise;
- private final AtomicBoolean stop = new AtomicBoolean(false);
+ public ClosedChannelHandler(final ReconnectPromise<?, ?> promise) {
+ this.promise = promise;
+ }
@Override
- public void operationComplete(final Future<Void> future) throws Exception {
- if (stop.get()) {
+ public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
+ if (promise.isCancelled()) {
return;
}
- // Start reconnecting crashed session after negotiation was successful
- if (!negotiationFinished.get()) {
+ // Check if initial connection was fully finished. If the session was dropped during negotiation, reconnect will not happen.
+ // Session can be dropped during negotiation on purpose by the client side and would make no sense to initiate reconnect
+ if (promise.isInitialConnectFinished() == false) {
return;
}
- connect();
- }
-
- @Override
- public void close() {
- this.stop.set(true);
+ LOG.debug("Reconnecting after connection to {} was dropped", promise.address);
+ promise.connect();
}
}
- private void addChannelClosedListener(final ChannelFuture channelFuture) {
- channelFuture.addListener(closedChannelListener);
- }
-
- @Override
- public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
- closedChannelListener.close();
-
- if (super.cancel(mayInterruptIfRunning)) {
- this.pending.cancel(mayInterruptIfRunning);
- return true;
- }
-
- return false;
- }
}
import java.util.EventListener;
/**
- * Listener that receives session state informations. This interface should be
+ * Listener that receives session state information. This interface should be
* implemented by a protocol specific abstract class, that is extended by
* a final class that implements the methods.
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.Promise;
-
+import io.netty.util.concurrent.SucceededFuture;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.Mockito;
public class ServerTest {
SimpleDispatcher clientDispatcher, dispatcher;
- final SimpleSessionListener pce = new SimpleSessionListener();
-
SimpleSession session = null;
ChannelFuture server = null;
InetSocketAddress serverAddress;
private NioEventLoopGroup eventLoopGroup;
-
+ // Dedicated loop group for server, needed for testing reconnection client
+ // With dedicated server group we can simulate session drop by shutting only the server group down
+ private NioEventLoopGroup serverLoopGroup;
@Before
public void setUp() {
final int port = 10000 + (int)(10000 * Math.random());
serverAddress = new InetSocketAddress("127.0.0.1", port);
eventLoopGroup = new NioEventLoopGroup();
+ serverLoopGroup = new NioEventLoopGroup();
+ }
+
+ @After
+ public void tearDown() throws IOException, InterruptedException, ExecutionException {
+ if(server != null) {
+ this.server.channel().close();
+ }
+ this.eventLoopGroup.shutdownGracefully().get();
+ this.serverLoopGroup.shutdownGracefully().get();
+ try {
+ Thread.sleep(500);
+ } catch (final InterruptedException e) {
+ throw new RuntimeException(e);
+ }
}
@Test
- public void testConnectionEstablished() throws Exception {
+ public void testConnectionRefused() throws Exception {
+ this.clientDispatcher = getClientDispatcher();
+
+ final ReconnectStrategy mockReconnectStrategy = getMockedReconnectStrategy();
+
+ this.clientDispatcher.createClient(this.serverAddress,
+ mockReconnectStrategy, new SessionListenerFactory<SimpleSessionListener>() {
+ @Override
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
+ }
+ });
+
+ Mockito.verify(mockReconnectStrategy, timeout(5000).atLeast(2)).scheduleReconnect(any(Throwable.class));
+ }
+
+ @Test
+ public void testConnectionReestablishInitial() throws Exception {
+ this.clientDispatcher = getClientDispatcher();
+
+ final ReconnectStrategy mockReconnectStrategy = getMockedReconnectStrategy();
+
+ this.clientDispatcher.createClient(this.serverAddress,
+ mockReconnectStrategy, new SessionListenerFactory<SimpleSessionListener>() {
+ @Override
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
+ }
+ });
+
+ Mockito.verify(mockReconnectStrategy, timeout(5000).atLeast(2)).scheduleReconnect(any(Throwable.class));
+
+ final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
+ this.dispatcher = getServerDispatcher(p);
+
+ this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
+ @Override
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
+ }
+ });
+
+ this.server.get();
+
+ assertEquals(true, p.get(3, TimeUnit.SECONDS));
+ }
+
+ @Test
+ public void testConnectionDrop() throws Exception {
final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
- this.dispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+ this.dispatcher = getServerDispatcher(p);
+ this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
@Override
- public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
- final Channel channel, final Promise<SimpleSession> promise) {
- p.setSuccess(true);
- return new SimpleSessionNegotiator(promise, channel);
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
}
- }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+ });
+
+ this.server.get();
+
+ this.clientDispatcher = getClientDispatcher();
+
+ final ReconnectStrategy reconnectStrategy = getMockedReconnectStrategy();
+ this.session = this.clientDispatcher.createClient(this.serverAddress,
+ reconnectStrategy, new SessionListenerFactory<SimpleSessionListener>() {
+ @Override
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
+ }
+ }).get(6, TimeUnit.SECONDS);
+
+ assertEquals(true, p.get(3, TimeUnit.SECONDS));
+
+ shutdownServer();
+
+ // No reconnect should be scheduled after server drops connection with not-reconnecting client
+ verify(reconnectStrategy, times(0)).scheduleReconnect(any(Throwable.class));
+ }
+
+ @Test
+ public void testConnectionReestablishAfterDrop() throws Exception {
+ final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
+
+ this.dispatcher = getServerDispatcher(p);
this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
@Override
this.server.get();
- this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+ this.clientDispatcher = getClientDispatcher();
+
+ final ReconnectStrategyFactory reconnectStrategyFactory = mock(ReconnectStrategyFactory.class);
+ final ReconnectStrategy reconnectStrategy = getMockedReconnectStrategy();
+ doReturn(reconnectStrategy).when(reconnectStrategyFactory).createReconnectStrategy();
+
+ this.clientDispatcher.createReconnectingClient(this.serverAddress,
+ reconnectStrategyFactory, new SessionListenerFactory<SimpleSessionListener>() {
+ @Override
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
+ }
+ });
+
+ assertEquals(true, p.get(3, TimeUnit.SECONDS));
+ shutdownServer();
+
+ verify(reconnectStrategyFactory, timeout(20000).atLeast(2)).createReconnectStrategy();
+ }
+
+ @Test
+ public void testConnectionEstablished() throws Exception {
+ final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
+
+ this.dispatcher = getServerDispatcher(p);
+
+ this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
@Override
- public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
- final Channel channel, final Promise<SimpleSession> promise) {
- return new SimpleSessionNegotiator(promise, channel);
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
}
- }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+ });
+
+ this.server.get();
+
+ this.clientDispatcher = getClientDispatcher();
this.session = this.clientDispatcher.createClient(this.serverAddress,
new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000), new SessionListenerFactory<SimpleSessionListener>() {
public void testConnectionFailed() throws IOException, InterruptedException, ExecutionException, TimeoutException {
final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
- this.dispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
-
- @Override
- public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
- final Channel channel, final Promise<SimpleSession> promise) {
- p.setSuccess(true);
- return new SimpleSessionNegotiator(promise, channel);
- }
- }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+ this.dispatcher = getServerDispatcher(p);
this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
@Override
this.server.get();
- this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
- @Override
- public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
- final Channel channel, final Promise<SimpleSession> promise) {
- return new SimpleSessionNegotiator(promise, channel);
- }
- }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+ this.clientDispatcher = getClientDispatcher();
this.session = this.clientDispatcher.createClient(this.serverAddress,
new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000), new SessionListenerFactory<SimpleSessionListener>() {
assertFalse(session.isSuccess());
}
- @After
- public void tearDown() throws IOException, InterruptedException {
- this.server.channel().close();
- this.eventLoopGroup.shutdownGracefully();
- try {
- Thread.sleep(500);
- } catch (final InterruptedException e) {
- throw new RuntimeException(e);
- }
+ @Test
+ public void testNegotiationFailedNoReconnect() throws Exception {
+ final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
+
+ this.dispatcher = getServerDispatcher(p);
+
+ this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
+ @Override
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
+ }
+ });
+
+ this.server.get();
+
+ this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+ @Override
+ public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
+ final Channel channel, final Promise<SimpleSession> promise) {
+
+ return new SimpleSessionNegotiator(promise, channel) {
+ @Override
+ protected void startNegotiation() throws Exception {
+ negotiationFailed(new IllegalStateException("Negotiation failed"));
+ }
+ };
+ }
+ }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+
+ final ReconnectStrategyFactory reconnectStrategyFactory = mock(ReconnectStrategyFactory.class);
+ final ReconnectStrategy reconnectStrategy = getMockedReconnectStrategy();
+ doReturn(reconnectStrategy).when(reconnectStrategyFactory).createReconnectStrategy();
+
+ this.clientDispatcher.createReconnectingClient(this.serverAddress,
+ reconnectStrategyFactory, new SessionListenerFactory<SimpleSessionListener>() {
+ @Override
+ public SimpleSessionListener getSessionListener() {
+ return new SimpleSessionListener();
+ }
+ });
+
+
+ // Only one strategy should be created for initial connect, no more = no reconnects
+ verify(reconnectStrategyFactory, times(1)).createReconnectStrategy();
}
+
+ private SimpleDispatcher getClientDispatcher() {
+ return new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+ @Override
+ public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
+ final Channel channel, final Promise<SimpleSession> promise) {
+ return new SimpleSessionNegotiator(promise, channel);
+ }
+ }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+ }
+
+ private ReconnectStrategy getMockedReconnectStrategy() throws Exception {
+ final ReconnectStrategy mockReconnectStrategy = mock(ReconnectStrategy.class);
+ final Future<Void> future = new SucceededFuture<>(GlobalEventExecutor.INSTANCE, null);
+ doReturn(future).when(mockReconnectStrategy).scheduleReconnect(any(Throwable.class));
+ doReturn(5000).when(mockReconnectStrategy).getConnectTimeout();
+ doNothing().when(mockReconnectStrategy).reconnectSuccessful();
+ return mockReconnectStrategy;
+ }
+
+
+ private void shutdownServer() throws InterruptedException, ExecutionException {
+ // Shutdown server
+ server.channel().close().get();
+ // Closing server channel does not close established connections, eventLoop has to be closed as well to simulate dropped session
+ serverLoopGroup.shutdownGracefully().get();
+ }
+
+ private SimpleDispatcher getServerDispatcher(final Promise<Boolean> p) {
+ return new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+
+ @Override
+ public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
+ final Channel channel, final Promise<SimpleSession> promise) {
+ p.setSuccess(true);
+ return new SimpleSessionNegotiator(promise, channel);
+ }
+ }, null, serverLoopGroup);
+ }
+
}
return super.createClient(address, strategy, new SimplePipelineInitializer(listenerFactory));
}
+ public Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory strategy, final SessionListenerFactory<SimpleSessionListener> listenerFactory) {
+ return super.createReconnectingClient(address, strategy, new SimplePipelineInitializer(listenerFactory));
+ }
+
public ChannelFuture createServer(final InetSocketAddress address, final SessionListenerFactory<SimpleSessionListener> listenerFactory) {
return super.createServer(address, new SimplePipelineInitializer(listenerFactory));
}
import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.osgi.framework.BundleContext;
/**
public CodecRegistryProvider(final ClassLoadingStrategy classLoadingStrategy, final BundleContext context) {
service = new RuntimeGeneratedMappingServiceImpl(CLASS_POOL, classLoadingStrategy);
registration = OsgiRegistrationUtil.registerService(context, service,
- SchemaServiceListener.class, BindingIndependentMappingService.class);
+ SchemaContextListener.class, BindingIndependentMappingService.class);
}
public CodecRegistry getCodecRegistry() {
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-subsystem</artifactId>
+ <version>0.2.5-SNAPSHOT</version>
+ </parent>
+ <artifactId>config-netty-config</artifactId>
+ <description>Configuration files for sal-rest-connector</description>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-artifacts</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>${project.build.directory}/classes/initial/00-netty.xml</file>
+ <type>xml</type>
+ <classifier>config</classifier>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
<module>shutdown-impl</module>
<module>netconf-config-dispatcher</module>
<module>config-module-archetype</module>
+ <module>config-netty-config</module>
</modules>
<dependencies>
<phase>generate-resources</phase>
<configuration>
<outputDirectory>${project.build.directory}/configuration</outputDirectory>
- <includeArtifactIds>sal-rest-connector-config</includeArtifactIds>
+ <includeArtifactIds>sal-rest-connector-config,config-netty-config,md-sal-config,netconf-config,toaster-config,netconf-connector-config</includeArtifactIds>
<includes>**\/*.xml</includes>
<excludeTransitive>true</excludeTransitive>
<ignorePermissions>false</ignorePermissions>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-rest-connector-config</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-netty-config</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>md-sal-config</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-config</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-connector-config</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>toaster-config</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-rest-docgen</artifactId>
<phase>generate-resources</phase>
<configuration>
<outputDirectory>${project.build.directory}/configuration</outputDirectory>
- <includeArtifactIds>sal-rest-connector-config</includeArtifactIds>
+ <includeArtifactIds>sal-rest-connector-config,config-netty-config,md-sal-config,netconf-config,toaster-config,netconf-connector-config</includeArtifactIds>
<includes>**\/*.xml</includes>
<excludeTransitive>true</excludeTransitive>
<ignorePermissions>false</ignorePermissions>
--- /dev/null
+package org.opendaylight.controller.hosttracker;
+
+import java.util.List;
+
+public interface IHostTrackerShell{
+
+ public List<String> dumpPendingArpReqList();
+ public List<String> dumpFailedArpReqList();
+}
\ No newline at end of file
import org.apache.felix.dm.Component;
import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
import org.opendaylight.controller.clustering.services.IClusterContainerServices;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
import org.opendaylight.controller.hosttracker.IfHostListener;
import org.opendaylight.controller.hosttracker.IfIptoHost;
import org.opendaylight.controller.hosttracker.IfNewHostNotify;
IInventoryListener.class.getName(),
IfIptoHost.class.getName(),
IfHostListener.class.getName(),
+ IHostTrackerShell.class.getName(),
ITopologyManagerAware.class.getName(),
ICacheUpdateAware.class.getName() }, props);
import org.opendaylight.controller.clustering.services.IClusterServices;
import org.opendaylight.controller.hosttracker.HostIdFactory;
import org.opendaylight.controller.hosttracker.IHostId;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
import org.opendaylight.controller.hosttracker.IPHostId;
import org.opendaylight.controller.hosttracker.IPMacHostId;
import org.opendaylight.controller.hosttracker.IfHostListener;
*
*/
-public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAware, IInventoryListener,
+public class HostTracker implements IfIptoHost, IfHostListener, IHostTrackerShell, ISwitchManagerAware, IInventoryListener,
ITopologyManagerAware, ICacheUpdateAware<IHostId, HostNodeConnector>, CommandProvider {
static final String ACTIVE_HOST_CACHE = "hosttracker.ActiveHosts";
static final String INACTIVE_HOST_CACHE = "hosttracker.InactiveHosts";
IHostId id = HostIdFactory.create(addr, null);
return getHostNetworkHierarchy(id);
}
+
+ @Override
+ public List<String> dumpPendingArpReqList() {
+ ARPPending arphost;
+ List<String> arpReq = new ArrayList<String>();
+ for (Entry<IHostId, ARPPending> entry : ARPPendingList.entrySet()) {
+ arpReq.add(entry.getValue().getHostId().toString());
+ }
+ return arpReq;
+ }
+
+ @Override
+ public List<String> dumpFailedArpReqList() {
+ ARPPending arphost;
+ List<String> arpReq = new ArrayList<String>();
+ for (Entry<IHostId, ARPPending> entry : failedARPReqList.entrySet()) {
+ arpReq.add(entry.getValue().getHostId().toString());
+ }
+ return arpReq;
+ }
}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>commons.opendaylight</artifactId>
+ <version>1.4.2-SNAPSHOT</version>
+ <relativePath>../../commons/opendaylight</relativePath>
+ </parent>
+ <artifactId>hosttracker.shell</artifactId>
+ <version>${hosttracker.shell.version}</version>
+ <packaging>bundle</packaging>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.karaf.shell</groupId>
+ <artifactId>org.apache.karaf.shell.console</artifactId>
+ <version>3.0.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>hosttracker.implementation</artifactId>
+ <version>${hosttracker.implementation.version}</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <version>${bundle.plugin.version}</version>
+ <configuration>
+ <instructions>
+ <Import-Package>org.apache.felix.service.command,
+ org.apache.karaf.shell.commands,
+ org.apache.karaf.shell.console,
+ *</Import-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
--- /dev/null
+package org.opendaylight.controller.hosttracker.shell;
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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
+*/
+
+import org.apache.felix.gogo.commands.Command;
+import org.apache.karaf.shell.console.OsgiCommandSupport;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
+
+@Command(scope = "hosttracker", name = "dumpFailedARPReqList", description="Display the dump failed ARPReqList")
+public class DumpFailedARPReqList extends OsgiCommandSupport{
+
+ private IHostTrackerShell hostTracker;
+
+ @Override
+ protected Object doExecute() throws Exception {
+ System.out.print(hostTracker.dumpFailedArpReqList());
+ return null;
+ }
+
+ public void setHostTracker(IHostTrackerShell hostTracker){
+ this.hostTracker = hostTracker;
+ }
+}
--- /dev/null
+package org.opendaylight.controller.hosttracker.shell;
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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
+*/
+
+import org.apache.felix.gogo.commands.Command;
+import org.apache.karaf.shell.console.OsgiCommandSupport;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
+
+@Command(scope = "hosttracker", name = "dumpPendingARPReqList", description="Display the dump pending ARPReqList")
+public class DumpPendingARPReqList extends OsgiCommandSupport{
+
+ private IHostTrackerShell hostTracker;
+
+ @Override
+ protected Object doExecute() throws Exception {
+ System.out.print(hostTracker.dumpPendingArpReqList());
+ return null;
+ }
+
+ public void setHostTracker(IHostTrackerShell hostTracker){
+ this.hostTracker = hostTracker;
+ }
+}
\ No newline at end of file
--- /dev/null
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
+ <reference id="HostTrackerRef" interface="org.opendaylight.controller.hosttracker.IHostTrackerShell"/>
+
+ <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
+
+ <command>
+ <action class="org.opendaylight.controller.hosttracker.shell.DumpFailedARPReqList">
+ <property name="hostTracker" ref="HostTrackerRef"/>
+ </action>
+ </command>
+ <command>
+ <action class="org.opendaylight.controller.hosttracker.shell.DumpPendingARPReqList">
+ <property name="hostTracker" ref="HostTrackerRef"/>
+ </action>
+ </command>
+ </command-bundle>
+</blueprint>
--- /dev/null
+package org.opendaylight.controller.hosttracker.shell;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
+
+public class HostTrackerShellTest {
+
+ private final long COMMAND_TIMEOUT = 1000;
+ private IHostTrackerShell hostTracker;
+
+ @Test
+ public void testDumpPendingARPReqList() throws Exception {
+ DumpPendingARPReqList dumpPendTest = new DumpPendingARPReqList();
+ hostTracker = mock(IHostTrackerShell.class);
+ List<String> failedList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
+ when(hostTracker.dumpPendingArpReqList()).thenReturn(failedList);
+ dumpPendTest.setHostTracker(hostTracker);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(baos));
+ dumpPendTest.doExecute();
+ //Assert.assertTrue(true);
+ Assert.assertEquals("[a, b, c]", baos.toString());
+ }
+
+ @Test
+ public void testDumpFailedARPReqList() throws Exception {
+ DumpFailedARPReqList dumpFailTest = new DumpFailedARPReqList();
+ hostTracker = mock(IHostTrackerShell.class);
+ List<String> failedList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
+ when(hostTracker.dumpFailedArpReqList()).thenReturn(failedList);
+ dumpFailTest.setHostTracker(hostTracker);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(baos));
+ dumpFailTest.doExecute();
+ //Assert.assertTrue(true);
+ Assert.assertEquals("[a, b, c]", baos.toString());
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-parent</artifactId>
+ <version>1.1-SNAPSHOT</version>
+ </parent>
+ <artifactId>md-sal-config</artifactId>
+ <description>Configuration files for md-sal</description>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-artifacts</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>${project.build.directory}/classes/initial/01-md-sal.xml</file>
+ <type>xml</type>
+ <classifier>config</classifier>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
</schema-service>
</module>
-->
- <!-- Cluster RPC -->
- <!-- Enable the following module if you want to use remote rpc connector
- <module>
- <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:remote-rpc-connector">prefix:remote-rpc-connector</type>
- <name>remote-rpc-connector</name>
- <dom-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:config:remote-rpc-connector">
- <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
- <name>dom-broker</name>
- </dom-broker>
- </module>
- -->
+
<module>
<type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:inmemory-datastore-provider">prefix:inmemory-operational-datastore-provider</type>
<name>operational-store-service</name>
</binding-mapping-service>
</binding-forwarded-data-broker>
</module>
+ <!-- Cluster RPC -->
+ <!-- Enable the following module if you want to use remote rpc connector
+ <module>
+ <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:remote-rpc-connector">prefix:remote-rpc-connector</type>
+ <name>remote-rpc-connector</name>
+ <dom-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:config:remote-rpc-connector">
+ <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:dom-broker-osgi-registry</type>
+ <name>dom-broker</name>
+ </dom-broker>
+ </module>
+ -->
</modules>
<services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
<service>
<module>sal-binding-util</module>
+ <!-- Configuration File -->
+ <module>md-sal-config</module>
+
<!-- Samples -->
<module>samples</module>
<!--sal-protocolbuffer-encoding-->
<module>sal-protocolbuffer-encoding</module>
- <!--sal-distributed-datastore-->
+ <!-- sal-distributed-datastore -->
<module>sal-distributed-datastore</module>
+ <!-- XSQL -->
+ <module>sal-dom-xsql</module>
+
<!-- Yang Test Models for MD-SAL -->
<module>sal-test-model</module>
+
+ <!-- Clustering -->
+ <module>sal-remoterpc-connector</module>
</modules>
<build>
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.japi.Creator;
+import com.google.common.base.Optional;
import org.opendaylight.controller.cluster.example.messages.KeyValue;
import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
import org.opendaylight.controller.cluster.example.messages.PrintRole;
import org.opendaylight.controller.cluster.example.messages.PrintState;
+import org.opendaylight.controller.cluster.raft.ConfigParams;
import org.opendaylight.controller.cluster.raft.RaftActor;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
private long persistIdentifier = 1;
- public ExampleActor(String id, Map<String, String> peerAddresses) {
- super(id, peerAddresses);
+ public ExampleActor(String id, Map<String, String> peerAddresses,
+ Optional<ConfigParams> configParams) {
+ super(id, peerAddresses, configParams);
}
- public static Props props(final String id, final Map<String, String> peerAddresses){
+ public static Props props(final String id, final Map<String, String> peerAddresses,
+ final Optional<ConfigParams> configParams){
return Props.create(new Creator<ExampleActor>(){
@Override public ExampleActor create() throws Exception {
- return new ExampleActor(id, peerAddresses);
+ return new ExampleActor(id, peerAddresses, configParams);
}
});
}
}
} else if (message instanceof PrintState) {
- LOG.debug("State of the node:"+getId() + " has = "+state.size() + " entries");
+ LOG.debug("State of the node:{} has entries={}, {}",
+ getId(), state.size(), getReplicatedLogState());
} else if (message instanceof PrintRole) {
- LOG.debug(getId() + " = " + getRaftState());
+ LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),getPeers());
+
} else {
super.onReceiveCommand(message);
}
@Override protected void applySnapshot(Object snapshot) {
state.clear();
state.putAll((HashMap) snapshot);
+ LOG.debug("Snapshot applied to state :" + ((HashMap) snapshot).size());
}
@Override public void onReceiveRecover(Object message) {
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.example;
+
+import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
+
+/**
+ * Implementation of ConfigParams for Example
+ */
+public class ExampleConfigParamsImpl extends DefaultConfigParamsImpl {
+ @Override
+ public long getSnapshotBatchCount() {
+ return 50;
+ }
+}
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.PoisonPill;
+import com.google.common.base.Optional;
import org.opendaylight.controller.cluster.example.messages.KeyValue;
+import org.opendaylight.controller.cluster.raft.ConfigParams;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception{
ActorRef example1Actor =
actorSystem.actorOf(ExampleActor.props("example-1",
- withoutPeer("example-1")), "example-1");
+ withoutPeer("example-1"), Optional.<ConfigParams>absent()), "example-1");
ActorRef example2Actor =
actorSystem.actorOf(ExampleActor.props("example-2",
- withoutPeer("example-2")), "example-2");
+ withoutPeer("example-2"), Optional.<ConfigParams>absent()), "example-2");
ActorRef example3Actor =
actorSystem.actorOf(ExampleActor.props("example-3",
- withoutPeer("example-3")), "example-3");
+ withoutPeer("example-3"), Optional.<ConfigParams>absent()), "example-3");
List<ActorRef> examples = Arrays.asList(example1Actor, example2Actor, example3Actor);
String actorName = "example-" + i;
examples.add(i - 1,
actorSystem.actorOf(ExampleActor.props(actorName,
- withoutPeer(actorName)), actorName));
+ withoutPeer(actorName), Optional.<ConfigParams>absent()),
+ actorName));
System.out.println("Created actor : " + actorName);
continue;
}
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
+import com.google.common.base.Optional;
import org.opendaylight.controller.cluster.example.messages.PrintRole;
import org.opendaylight.controller.cluster.example.messages.PrintState;
+import org.opendaylight.controller.cluster.raft.ConfigParams;
import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer;
import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
-import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
* This is a test driver for testing akka-raft implementation
* Its uses ExampleActors and threads to push content(key-vals) to these actors
* Each ExampleActor can have one or more ClientActors. Each ClientActor spawns
- * a thread and starts push logs to the actor its assignged to.
+ * a thread and starts push logs to the actor its assigned to.
*/
public class TestDriver {
private static Map<String, String> allPeers = new HashMap<>();
private static Map<String, ActorRef> clientActorRefs = new HashMap<String, ActorRef>();
private static Map<String, ActorRef> actorRefs = new HashMap<String, ActorRef>();
- private static LogGenerator logGenerator = new LogGenerator();;
+ private static LogGenerator logGenerator = new LogGenerator();
+ private int nameCounter = 0;
+ private static ConfigParams configParams = new ExampleConfigParamsImpl();
/**
* Create nodes, add clients and start logging.
* createNodes:{num}
* addNodes:{num}
* stopNode:{nodeName}
+ * reinstateNode:{nodeName}
* addClients:{num}
* addClientsToNode:{nodeName, num}
* startLogging
String[] arr = command.split(":");
td.stopNode(arr[1]);
+ } else if (command.startsWith("reinstateNode")) {
+ String[] arr = command.split(":");
+ td.reinstateNode(arr[1]);
+
} else if (command.startsWith("startLogging")) {
td.startAllLogging();
}
}
+ public static ActorRef createExampleActor(String name) {
+ return actorSystem.actorOf(ExampleActor.props(name, withoutPeer(name),
+ Optional.of(configParams)), name);
+ }
+
public void createNodes(int num) {
for (int i=0; i < num; i++) {
- int rand = getUnusedRandom(num);
- allPeers.put("example-"+rand, "akka://default/user/example-"+rand);
+ nameCounter = nameCounter + 1;
+ allPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter);
}
for (String s : allPeers.keySet()) {
- ActorRef exampleActor = actorSystem.actorOf(
- ExampleActor.props(s, withoutPeer(s)), s);
+ ActorRef exampleActor = createExampleActor(s);
actorRefs.put(s, exampleActor);
System.out.println("Created node:"+s);
public void addNodes(int num) {
Map<String, String> newPeers = new HashMap<>();
for (int i=0; i < num; i++) {
- int rand = getUnusedRandom(num);
- newPeers.put("example-"+rand, "akka://default/user/example-"+rand);
- allPeers.put("example-"+rand, "akka://default/user/example-"+rand);
+ nameCounter = nameCounter + 1;
+ newPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter);
+ allPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter);
}
Map<String, ActorRef> newActorRefs = new HashMap<String, ActorRef>(num);
for (Map.Entry<String, String> entry : newPeers.entrySet()) {
- ActorRef exampleActor = actorSystem.actorOf(
- ExampleActor.props(entry.getKey(), withoutPeer(entry.getKey())), entry.getKey());
+ ActorRef exampleActor = createExampleActor(entry.getKey());
newActorRefs.put(entry.getKey(), exampleActor);
//now also add these new nodes as peers from the previous nodes
public void addClientsToNode(String actorName, int num) {
ActorRef actorRef = actorRefs.get(actorName);
for (int i=0; i < num; i++) {
- String clientName = "client-" + i + "-" + actorRef;
+ String clientName = "client-" + i + "-" + actorName;
clientActorRefs.put(clientName,
actorSystem.actorOf(ClientActor.props(actorRef), clientName));
System.out.println("Added client-node:" + clientName);
public void stopNode(String actorName) {
ActorRef actorRef = actorRefs.get(actorName);
- String clientName = "client-"+actorName;
- if(clientActorRefs.containsKey(clientName)) {
- actorSystem.stop(clientActorRefs.get(clientName));
- clientActorRefs.remove(clientName);
+
+ for (Map.Entry<String,ActorRef> entry : clientActorRefs.entrySet()) {
+ if (entry.getKey().endsWith(actorName)) {
+ actorSystem.stop(entry.getValue());
+ }
}
+
actorSystem.stop(actorRef);
actorRefs.remove(actorName);
}
allPeers.remove(actorName);
+ }
+ public void reinstateNode(String actorName) {
+ String address = "akka://default/user/"+actorName;
+ allPeers.put(actorName, address);
+
+ ActorRef exampleActor = createExampleActor(actorName);
+
+ for (ActorRef actor : actorRefs.values()) {
+ actor.tell(new AddRaftPeer(actorName, address), null);
+ }
+
+ actorRefs.put(actorName, exampleActor);
+
+ addClientsToNode(actorName, 1);
}
public void startAllLogging() {
return null;
}
- private int getUnusedRandom(int num) {
- int rand = -1;
- do {
- rand = (new Random()).nextInt(num * num);
- } while (allPeers.keySet().contains("example-"+rand));
-
- return rand;
- }
private static Map<String, String> withoutPeer(String peerId) {
Map<String, String> without = new ConcurrentHashMap<>(allPeers);
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.raft;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Abstract class handling the mapping of
+ * logical LogEntry Index and the physical list index.
+ */
+public abstract class AbstractReplicatedLogImpl implements ReplicatedLog {
+
+ protected final List<ReplicatedLogEntry> journal;
+ protected final Object snapshot;
+ protected long snapshotIndex = -1;
+ protected long snapshotTerm = -1;
+
+ public AbstractReplicatedLogImpl(Object state, long snapshotIndex,
+ long snapshotTerm, List<ReplicatedLogEntry> unAppliedEntries) {
+ this.snapshot = state;
+ this.snapshotIndex = snapshotIndex;
+ this.snapshotTerm = snapshotTerm;
+ this.journal = new ArrayList<>(unAppliedEntries);
+ }
+
+
+ public AbstractReplicatedLogImpl() {
+ this.snapshot = null;
+ this.journal = new ArrayList<>();
+ }
+
+ protected int adjustedIndex(long logEntryIndex) {
+ if(snapshotIndex < 0){
+ return (int) logEntryIndex;
+ }
+ return (int) (logEntryIndex - (snapshotIndex + 1));
+ }
+
+ @Override
+ public ReplicatedLogEntry get(long logEntryIndex) {
+ int adjustedIndex = adjustedIndex(logEntryIndex);
+
+ if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
+ // physical index should be less than list size and >= 0
+ return null;
+ }
+
+ return journal.get(adjustedIndex);
+ }
+
+ @Override
+ public ReplicatedLogEntry last() {
+ if (journal.isEmpty()) {
+ return null;
+ }
+ // get the last entry directly from the physical index
+ return journal.get(journal.size() - 1);
+ }
+
+ @Override
+ public long lastIndex() {
+ if (journal.isEmpty()) {
+ // it can happen that after snapshot, all the entries of the
+ // journal are trimmed till lastApplied, so lastIndex = snapshotIndex
+ return snapshotIndex;
+ }
+ return last().getIndex();
+ }
+
+ @Override
+ public long lastTerm() {
+ if (journal.isEmpty()) {
+ // it can happen that after snapshot, all the entries of the
+ // journal are trimmed till lastApplied, so lastTerm = snapshotTerm
+ return snapshotTerm;
+ }
+ return last().getTerm();
+ }
+
+ @Override
+ public void removeFrom(long logEntryIndex) {
+ int adjustedIndex = adjustedIndex(logEntryIndex);
+ if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
+ // physical index should be less than list size and >= 0
+ return;
+ }
+ journal.subList(adjustedIndex , journal.size()).clear();
+ }
+
+ @Override
+ public void append(ReplicatedLogEntry replicatedLogEntry) {
+ journal.add(replicatedLogEntry);
+ }
+
+ @Override
+ public List<ReplicatedLogEntry> getFrom(long logEntryIndex) {
+ int adjustedIndex = adjustedIndex(logEntryIndex);
+ int size = journal.size();
+ List<ReplicatedLogEntry> entries = new ArrayList<>(100);
+ if (adjustedIndex >= 0 && adjustedIndex < size) {
+ // physical index should be less than list size and >= 0
+ entries.addAll(journal.subList(adjustedIndex, size));
+ }
+ return entries;
+ }
+
+ @Override
+ public long size() {
+ return journal.size();
+ }
+
+ @Override
+ public boolean isPresent(long logEntryIndex) {
+ if (logEntryIndex > lastIndex()) {
+ // if the request logical index is less than the last present in the list
+ return false;
+ }
+ int adjustedIndex = adjustedIndex(logEntryIndex);
+ return (adjustedIndex >= 0);
+ }
+
+ @Override
+ public boolean isInSnapshot(long logEntryIndex) {
+ return logEntryIndex <= snapshotIndex;
+ }
+
+ @Override
+ public Object getSnapshot() {
+ return snapshot;
+ }
+
+ @Override
+ public long getSnapshotIndex() {
+ return snapshotIndex;
+ }
+
+ @Override
+ public long getSnapshotTerm() {
+ return snapshotTerm;
+ }
+
+ @Override
+ public abstract void appendAndPersist(ReplicatedLogEntry replicatedLogEntry);
+
+ @Override
+ public abstract void removeFromAndPersist(long index);
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.raft;
+
+import scala.concurrent.duration.FiniteDuration;
+
+/**
+ * Configuration Parameter interface for configuring the Raft consensus system
+ * <p/>
+ * Any component using this implementation might want to provide an implementation of
+ * this interface to configure
+ *
+ * A default implementation will be used if none is provided.
+ *
+ * @author Kamal Rameshan
+ */
+public interface ConfigParams {
+ /**
+ * The minimum number of entries to be present in the in-memory Raft log
+ * for a snapshot to be taken
+ *
+ * @return long
+ */
+ public long getSnapshotBatchCount();
+
+ /**
+ * The interval at which a heart beat message will be sent to the remote
+ * RaftActor
+ *
+ * @return FiniteDuration
+ */
+ public FiniteDuration getHeartBeatInterval();
+
+ /**
+ * The interval in which a new election would get triggered if no leader is found
+ *
+ * Normally its set to atleast twice the heart beat interval
+ *
+ * @return FiniteDuration
+ */
+ public FiniteDuration getElectionTimeOutInterval();
+
+ /**
+ * The maximum election time variance. The election is scheduled using both
+ * the Election Timeout and Variance
+ *
+ * @return int
+ */
+ public int getElectionTimeVariance();
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.raft;
+
+import scala.concurrent.duration.FiniteDuration;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Default implementation of the ConfigParams
+ *
+ * If no implementation is provided for ConfigParams, then this will be used.
+ */
+public class DefaultConfigParamsImpl implements ConfigParams {
+
+ private static final int SNAPSHOT_BATCH_COUNT = 100000;
+
+ /**
+ * The maximum election time variance
+ */
+ private static final int ELECTION_TIME_MAX_VARIANCE = 100;
+
+
+ /**
+ * The interval at which a heart beat message will be sent to the remote
+ * RaftActor
+ * <p/>
+ * Since this is set to 100 milliseconds the Election timeout should be
+ * at least 200 milliseconds
+ */
+ protected static final FiniteDuration HEART_BEAT_INTERVAL =
+ new FiniteDuration(100, TimeUnit.MILLISECONDS);
+
+
+ @Override
+ public long getSnapshotBatchCount() {
+ return SNAPSHOT_BATCH_COUNT;
+ }
+
+ @Override
+ public FiniteDuration getHeartBeatInterval() {
+ return HEART_BEAT_INTERVAL;
+ }
+
+
+ @Override
+ public FiniteDuration getElectionTimeOutInterval() {
+ // returns 2 times the heart beat interval
+ return HEART_BEAT_INTERVAL.$times(2);
+ }
+
+ @Override
+ public int getElectionTimeVariance() {
+ return ELECTION_TIME_MAX_VARIANCE;
+ }
+}
import akka.persistence.SnapshotOffer;
import akka.persistence.SnapshotSelectionCriteria;
import akka.persistence.UntypedPersistentActor;
+import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
+import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
+import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
+import com.google.common.base.Optional;
import org.opendaylight.controller.cluster.raft.behaviors.Candidate;
import org.opendaylight.controller.cluster.raft.behaviors.Follower;
import org.opendaylight.controller.cluster.raft.behaviors.Leader;
import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
-import org.opendaylight.controller.cluster.raft.internal.messages.ApplySnapshot;
import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer;
-import org.opendaylight.controller.cluster.raft.internal.messages.ApplyState;
-import org.opendaylight.controller.cluster.raft.internal.messages.Replicate;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
import java.io.Serializable;
-import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public RaftActor(String id, Map<String, String> peerAddresses) {
+ this(id, peerAddresses, Optional.<ConfigParams>absent());
+ }
+
+ public RaftActor(String id, Map<String, String> peerAddresses,
+ Optional<ConfigParams> configParams) {
+
context = new RaftActorContextImpl(this.getSelf(),
- this.getContext(),
- id, new ElectionTermImpl(),
- -1, -1, replicatedLog, peerAddresses, LOG);
+ this.getContext(), id, new ElectionTermImpl(),
+ -1, -1, replicatedLog, peerAddresses,
+ (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
+ LOG);
}
@Override public void onReceiveRecover(Object message) {
if (message instanceof SnapshotOffer) {
+ LOG.debug("SnapshotOffer called..");
SnapshotOffer offer = (SnapshotOffer) message;
Snapshot snapshot = (Snapshot) offer.snapshot();
// when we need to install it on a peer
replicatedLog = new ReplicatedLogImpl(snapshot);
+ context.setReplicatedLog(replicatedLog);
+
+ LOG.debug("Applied snapshot to replicatedLog. " +
+ "snapshotIndex={}, snapshotTerm={}, journal-size={}",
+ replicatedLog.snapshotIndex, replicatedLog.snapshotTerm,
+ replicatedLog.size());
+
// Apply the snapshot to the actors state
applySnapshot(snapshot.getState());
context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), ((UpdateElectionTerm) message).getVotedFor());
} else if (message instanceof RecoveryCompleted) {
LOG.debug(
- "Last index in log : " + replicatedLog.lastIndex());
+ "RecoveryCompleted - Switching actor to Follower - " +
+ "Last index in log:{}, snapshotIndex={}, snapshotTerm={}, " +
+ "journal-size={}",
+ replicatedLog.lastIndex(), replicatedLog.snapshotIndex,
+ replicatedLog.snapshotTerm, replicatedLog.size());
currentBehavior = switchBehavior(RaftState.Follower);
}
}
}
}
+ public java.util.Set<String> getPeers() {
+ return context.getPeerAddresses().keySet();
+ }
+
+ protected String getReplicatedLogState() {
+ return "snapshotIndex=" + context.getReplicatedLog().getSnapshotIndex()
+ + ", snapshotTerm=" + context.getReplicatedLog().getSnapshotTerm()
+ + ", im-mem journal size=" + context.getReplicatedLog().size();
+ }
/**
return currentBehavior.state();
}
+ /**
+ * setPeerAddress sets the address of a known peer at a later time.
+ * <p>
+ * This is to account for situations where a we know that a peer
+ * exists but we do not know an address up-front. This may also be used in
+ * situations where a known peer starts off in a different location and we
+ * need to change it's address
+ * <p>
+ * Note that if the peerId does not match the list of peers passed to
+ * this actor during construction an IllegalStateException will be thrown.
+ *
+ * @param peerId
+ * @param peerAddress
+ */
+ protected void setPeerAddress(String peerId, String peerAddress){
+ context.setPeerAddress(peerId, peerAddress);
+ }
+
/**
}
private void trimPersistentData(long sequenceNumber) {
- // Trim snapshots
+ // Trim akka snapshots
// FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied
// For now guessing that it is ANDed.
deleteSnapshots(new SnapshotSelectionCriteria(
- sequenceNumber - 100000, 43200000));
+ sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
- // Trim journal
+ // Trim akka journal
deleteMessages(sequenceNumber);
}
- private class ReplicatedLogImpl implements ReplicatedLog {
- private final List<ReplicatedLogEntry> journal;
- private final Object snapshot;
- private long snapshotIndex = -1;
- private long snapshotTerm = -1;
+ private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
public ReplicatedLogImpl(Snapshot snapshot) {
- this.snapshot = snapshot.getState();
- this.snapshotIndex = snapshot.getLastAppliedIndex();
- this.snapshotTerm = snapshot.getLastAppliedTerm();
-
- this.journal = new ArrayList<>(snapshot.getUnAppliedEntries());
+ super(snapshot.getState(),
+ snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
+ snapshot.getUnAppliedEntries());
}
public ReplicatedLogImpl() {
- this.snapshot = null;
- this.journal = new ArrayList<>();
- }
-
- @Override public ReplicatedLogEntry get(long index) {
- int adjustedIndex = adjustedIndex(index);
-
- if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
- return null;
- }
-
- return journal.get(adjustedIndex);
- }
-
- @Override public ReplicatedLogEntry last() {
- if (journal.size() == 0) {
- return null;
- }
- return get(journal.size() - 1);
- }
-
- @Override public long lastIndex() {
- if (journal.size() == 0) {
- return -1;
- }
-
- return last().getIndex();
- }
-
- @Override public long lastTerm() {
- if (journal.size() == 0) {
- return -1;
- }
-
- return last().getTerm();
+ super();
}
+ @Override public void removeFromAndPersist(long logEntryIndex) {
+ int adjustedIndex = adjustedIndex(logEntryIndex);
- @Override public void removeFrom(long index) {
- int adjustedIndex = adjustedIndex(index);
-
- if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
- return;
- }
-
- journal.subList(adjustedIndex , journal.size()).clear();
- }
-
-
- @Override public void removeFromAndPersist(long index) {
- int adjustedIndex = adjustedIndex(index);
-
- if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
+ if (adjustedIndex < 0) {
return;
}
//FIXME : Doing nothing for now
}
});
-
-
- }
-
- @Override public void append(
- final ReplicatedLogEntry replicatedLogEntry) {
- journal.add(replicatedLogEntry);
- }
-
- @Override public List<ReplicatedLogEntry> getFrom(long index) {
- int adjustedIndex = adjustedIndex(index);
-
- List<ReplicatedLogEntry> entries = new ArrayList<>(100);
- if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
- return entries;
- }
-
-
- for (int i = adjustedIndex;
- i < journal.size(); i++) {
- entries.add(journal.get(i));
- }
- return entries;
}
@Override public void appendAndPersist(
final String identifier,
final ReplicatedLogEntry replicatedLogEntry) {
context.getLogger().debug(
- "Append log entry and persist " + replicatedLogEntry);
+ "Append log entry and persist {} ", replicatedLogEntry);
// FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs
journal.add(replicatedLogEntry);
new Procedure<ReplicatedLogEntry>() {
public void apply(ReplicatedLogEntry evt) throws Exception {
// FIXME : Tentatively create a snapshot every hundred thousand entries. To be tuned.
- if (size() > 100000) {
- ReplicatedLogEntry lastAppliedEntry =
- get(context.getLastApplied());
+ if (journal.size() > context.getConfigParams().getSnapshotBatchCount()) {
+ LOG.info("Initiating Snapshot Capture..");
long lastAppliedIndex = -1;
long lastAppliedTerm = -1;
+
+ ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied());
if (lastAppliedEntry != null) {
lastAppliedIndex = lastAppliedEntry.getIndex();
lastAppliedTerm = lastAppliedEntry.getTerm();
}
- saveSnapshot(Snapshot.create(createSnapshot(),
+ LOG.debug("Snapshot Capture logSize: {}", journal.size());
+ LOG.debug("Snapshot Capture lastApplied:{} ", context.getLastApplied());
+ LOG.debug("Snapshot Capture lastAppliedIndex:{}", lastAppliedIndex);
+ LOG.debug("Snapshot Capture lastAppliedTerm:{}", lastAppliedTerm);
+
+ // create a snapshot object from the state provided and save it
+ // when snapshot is saved async, SaveSnapshotSuccess is raised.
+ Snapshot sn = Snapshot.create(createSnapshot(),
getFrom(context.getLastApplied() + 1),
lastIndex(), lastTerm(), lastAppliedIndex,
- lastAppliedTerm));
+ lastAppliedTerm);
+ saveSnapshot(sn);
+
+ LOG.info("Persisting of snapshot done:{}", sn.getLogMessage());
+
+ //be greedy and remove entries from in-mem journal which are in the snapshot
+ // and update snapshotIndex and snapshotTerm without waiting for the success,
+ // TODO: damage-recovery to be done on failure
+ journal.subList(0, (int) (lastAppliedIndex - snapshotIndex)).clear();
+ snapshotIndex = lastAppliedIndex;
+ snapshotTerm = lastAppliedTerm;
+
+ LOG.info("Removed in-memory snapshotted entries, " +
+ "adjusted snaphsotIndex:{}" +
+ "and term:{}", snapshotIndex, lastAppliedTerm);
}
// Send message for replication
if (clientActor != null) {
);
}
- @Override public long size() {
- return journal.size() + snapshotIndex + 1;
- }
-
- @Override public boolean isPresent(long index) {
- int adjustedIndex = adjustedIndex(index);
-
- if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
- return false;
- }
- return true;
- }
-
- @Override public boolean isInSnapshot(long index) {
- return index <= snapshotIndex;
- }
-
- @Override public Object getSnapshot() {
- return snapshot;
- }
-
- @Override public long getSnapshotIndex() {
- return snapshotIndex;
- }
-
- @Override public long getSnapshotTerm() {
- return snapshotTerm;
- }
-
- private int adjustedIndex(long index) {
- if(snapshotIndex < 0){
- return (int) index;
- }
- return (int) (index - snapshotIndex);
- }
}
-
-
-
private static class DeleteEntries implements Serializable {
private final int fromIndex;
public long getLastAppliedTerm() {
return lastAppliedTerm;
}
+
+ public String getLogMessage() {
+ StringBuilder sb = new StringBuilder();
+ return sb.append("Snapshot={")
+ .append("lastTerm:" + this.getLastTerm() + ", ")
+ .append("LastAppliedIndex:" + this.getLastAppliedIndex() + ", ")
+ .append("LastAppliedTerm:" + this.getLastAppliedTerm() + ", ")
+ .append("UnAppliedEntries size:" + this.getUnAppliedEntries().size() + "}")
+ .toString();
+
+ }
}
private class ElectionTermImpl implements ElectionTerm {
*/
void setLastApplied(long lastApplied);
+ /**
+ *
+ * @param replicatedLog
+ */
+ public void setReplicatedLog(ReplicatedLog replicatedLog);
+
/**
* @return A representation of the log
*/
ActorSystem getActorSystem();
/**
+ * Get the logger to be used for logging messages
*
* @return
*/
LoggingAdapter getLogger();
/**
- * Get a mapping of peer id's their addresses
+ * Get a mapping of peerId's to their addresses
+ *
* @return
+ *
*/
Map<String, String> getPeerAddresses();
/**
+ * Get the address of the peer as a String. This is the same format in
+ * which a consumer would provide the address
*
* @param peerId
- * @return
+ * @return The address of the peer or null if the address has not yet been
+ * resolved
*/
String getPeerAddress(String peerId);
* @param name
*/
public void removePeer(String name);
+
+ /**
+ * Given a peerId return the corresponding actor
+ * <p>
+ *
+ *
+ * @param peerId
+ * @return The actorSelection corresponding to the peer or null if the
+ * address has not yet been resolved
+ */
+ ActorSelection getPeerActorSelection(String peerId);
+
+ /**
+ * Set Peer Address can be called at a later time to change the address of
+ * a known peer.
+ *
+ * <p>
+ * Throws an IllegalStateException if the peer is unknown
+ *
+ * @param peerId
+ * @param peerAddress
+ */
+ void setPeerAddress(String peerId, String peerAddress);
+
+ /**
+ * @return ConfigParams
+ */
+ public ConfigParams getConfigParams();
}
import java.util.Map;
-public class RaftActorContextImpl implements RaftActorContext{
+import static com.google.common.base.Preconditions.checkState;
+
+public class RaftActorContextImpl implements RaftActorContext {
private final ActorRef actor;
private long lastApplied;
- private final ReplicatedLog replicatedLog;
+ private ReplicatedLog replicatedLog;
private final Map<String, String> peerAddresses;
private final LoggingAdapter LOG;
+ private final ConfigParams configParams;
public RaftActorContextImpl(ActorRef actor, UntypedActorContext context,
String id,
ElectionTerm termInformation, long commitIndex,
- long lastApplied, ReplicatedLog replicatedLog, Map<String, String> peerAddresses, LoggingAdapter logger) {
+ long lastApplied, ReplicatedLog replicatedLog,
+ Map<String, String> peerAddresses, ConfigParams configParams,
+ LoggingAdapter logger) {
this.actor = actor;
this.context = context;
this.id = id;
this.lastApplied = lastApplied;
this.replicatedLog = replicatedLog;
this.peerAddresses = peerAddresses;
+ this.configParams = configParams;
this.LOG = logger;
}
this.lastApplied = lastApplied;
}
+ @Override public void setReplicatedLog(ReplicatedLog replicatedLog) {
+ this.replicatedLog = replicatedLog;
+ }
+
@Override public ReplicatedLog getReplicatedLog() {
return replicatedLog;
}
return peerAddresses.get(peerId);
}
+ @Override public ConfigParams getConfigParams() {
+ return configParams;
+ }
+
@Override public void addToPeers(String name, String address) {
- LOG.debug("Kamal--> addToPeer for:"+name);
peerAddresses.put(name, address);
}
@Override public void removePeer(String name) {
- LOG.debug("Kamal--> removePeer for:"+name);
peerAddresses.remove(name);
}
+
+ @Override public ActorSelection getPeerActorSelection(String peerId) {
+ String peerAddress = getPeerAddress(peerId);
+ if(peerAddress != null){
+ return actorSelection(peerAddress);
+ }
+ return null;
+ }
+
+ @Override public void setPeerAddress(String peerId, String peerAddress) {
+ LOG.info("Peer address for peer {} set to {}", peerId, peerAddress);
+ checkState(peerAddresses.containsKey(peerId), peerId + " is unknown");
+
+ peerAddresses.put(peerId, peerAddress);
+ }
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import java.io.Serializable;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import akka.actor.ActorRef;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import java.io.Serializable;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import java.io.Serializable;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import java.io.Serializable;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import akka.actor.ActorRef;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import java.io.Serializable;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import java.io.Serializable;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.cluster.raft.internal.messages;
+package org.opendaylight.controller.cluster.raft.base.messages;
import java.io.Serializable;
import org.opendaylight.controller.cluster.raft.RaftState;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
import org.opendaylight.controller.cluster.raft.SerializationUtils;
-import org.opendaylight.controller.cluster.raft.internal.messages.ApplyState;
-import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
+import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
+import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
import org.opendaylight.controller.cluster.raft.messages.RequestVote;
*/
protected final RaftActorContext context;
- /**
- * The maximum election time variance
- */
- private static final int ELECTION_TIME_MAX_VARIANCE = 100;
-
- /**
- * The interval at which a heart beat message will be sent to the remote
- * RaftActor
- * <p/>
- * Since this is set to 100 milliseconds the Election timeout should be
- * at least 200 milliseconds
- */
- protected static final FiniteDuration HEART_BEAT_INTERVAL =
- new FiniteDuration(100, TimeUnit.MILLISECONDS);
-
- /**
- * The interval in which a new election would get triggered if no leader is found
- */
- private static final long ELECTION_TIME_INTERVAL =
- HEART_BEAT_INTERVAL.toMillis() * 2;
-
/**
*
*/
* @return
*/
protected FiniteDuration electionDuration() {
- long variance = new Random().nextInt(ELECTION_TIME_MAX_VARIANCE);
- return new FiniteDuration(ELECTION_TIME_INTERVAL + variance,
- TimeUnit.MILLISECONDS);
+ long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
+ return context.getConfigParams().getElectionTimeOutInterval().$plus(
+ new FiniteDuration(variance, TimeUnit.MILLISECONDS));
}
/**
import akka.actor.ActorSelection;
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
-import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
+import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
import org.opendaylight.controller.cluster.raft.messages.RequestVote;
import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.Set;
/**
* The behavior of a RaftActor when it is in the CandidateState
*/
public class Candidate extends AbstractRaftActorBehavior {
- private final Map<String, ActorSelection> peerToActor = new HashMap<>();
-
private int voteCount;
private final int votesRequired;
+ private final Set<String> peers;
+
public Candidate(RaftActorContext context) {
super(context);
- Collection<String> peerPaths = context.getPeerAddresses().values();
+ peers = context.getPeerAddresses().keySet();
- for (String peerPath : peerPaths) {
- peerToActor.put(peerPath,
- context.actorSelection(peerPath));
- }
+ context.getLogger().debug("Election:Candidate has following peers:"+ peers);
- context.getLogger().debug("Election:Candidate has following peers:"+peerToActor.keySet());
- if(peerPaths.size() > 0) {
+ if(peers.size() > 0) {
// Votes are required from a majority of the peers including self.
// The votesRequired field therefore stores a calculated value
// of the number of votes required for this candidate to win an
// 0 peers = 1 votesRequired (0 + 1) / 2 + 1 = 1
// 2 peers = 2 votesRequired (2 + 1) / 2 + 1 = 2
// 4 peers = 3 votesRequired (4 + 1) / 2 + 1 = 3
- int noOfPeers = peerPaths.size();
+ int noOfPeers = peers.size();
int self = 1;
votesRequired = (noOfPeers + self) / 2 + 1;
} else {
@Override protected RaftState handleAppendEntries(ActorRef sender,
AppendEntries appendEntries) {
+ context.getLogger().info("Candidate: Received {}", appendEntries.toString());
+
return state();
}
}
@Override
- public RaftState handleMessage(ActorRef sender, Object message) {
+ public RaftState handleMessage(ActorRef sender, Object originalMessage) {
+
+ Object message = fromSerializableMessage(originalMessage);
if (message instanceof RaftRPC) {
+
RaftRPC rpc = (RaftRPC) message;
+
+ context.getLogger().debug("RaftRPC message received {} my term is {}", rpc.toString(), context.getTermInformation().getCurrentTerm());
+
// If RPC request or response contains term T > currentTerm:
// set currentTerm = T, convert to follower (§5.1)
// This applies to all RPC messages and responses
scheduleElection(electionDuration());
return state();
}
+
return super.handleMessage(sender, message);
}
// Increment the election term and vote for self
long currentTerm = context.getTermInformation().getCurrentTerm();
- context.getTermInformation().updateAndPersist(currentTerm + 1, context.getId());
+ context.getTermInformation().updateAndPersist(currentTerm + 1,
+ context.getId());
- context.getLogger().debug("Starting new term " + (currentTerm+1));
+ context.getLogger().debug("Starting new term " + (currentTerm + 1));
// Request for a vote
// TODO: Retry request for vote if replies do not arrive in a reasonable
// amount of time TBD
- for (ActorSelection peerActor : peerToActor.values()) {
- peerActor.tell(new RequestVote(
- context.getTermInformation().getCurrentTerm(),
- context.getId(),
- context.getReplicatedLog().lastIndex(),
- context.getReplicatedLog().lastTerm()),
- context.getActor()
- );
+ for (String peerId : peers) {
+ ActorSelection peerActor = context.getPeerActorSelection(peerId);
+ if(peerActor != null) {
+ peerActor.tell(new RequestVote(
+ context.getTermInformation().getCurrentTerm(),
+ context.getId(),
+ context.getReplicatedLog().lastIndex(),
+ context.getReplicatedLog().lastTerm()),
+ context.getActor()
+ );
+ }
}
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
-import org.opendaylight.controller.cluster.raft.internal.messages.ApplySnapshot;
-import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
+import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
+import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
@Override protected RaftState handleAppendEntries(ActorRef sender,
AppendEntries appendEntries) {
+ if(appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
+ context.getLogger()
+ .info("Follower: Received {}", appendEntries.toString());
+ }
+
// TODO : Refactor this method into a bunch of smaller methods
// to make it easier to read. Before refactoring ensure tests
// cover the code properly
int addEntriesFrom = 0;
if (context.getReplicatedLog().size() > 0) {
- // Find the entry up until which the one that is not in the
- // follower's log
- for (int i = 0;
- i < appendEntries.getEntries()
- .size(); i++, addEntriesFrom++) {
- ReplicatedLogEntry matchEntry =
- appendEntries.getEntries().get(i);
- ReplicatedLogEntry newEntry = context.getReplicatedLog()
- .get(matchEntry.getIndex());
+ // Find the entry up until which the one that is not in the follower's log
+ for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
+ ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
+ ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
if (newEntry == null) {
//newEntry not found in the log
for (int i = addEntriesFrom;
i < appendEntries.getEntries().size(); i++) {
- context.getLogger().debug(
- "Append entry to log " + appendEntries.getEntries().get(i).getData()
+ context.getLogger().info(
+ "Append entry to log " + appendEntries.getEntries().get(
+ i).getData()
.toString()
);
context.getReplicatedLog()
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
-import org.opendaylight.controller.cluster.raft.internal.messages.ApplyState;
-import org.opendaylight.controller.cluster.raft.internal.messages.Replicate;
-import org.opendaylight.controller.cluster.raft.internal.messages.SendHeartBeat;
-import org.opendaylight.controller.cluster.raft.internal.messages.SendInstallSnapshot;
+import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
+import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
+import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
+import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
private final Map<String, FollowerLogInformation> followerToLog =
new HashMap();
- private final Map<String, ActorSelection> followerToActor = new HashMap<>();
+ private final Set<String> followers;
private Cancellable heartbeatSchedule = null;
private Cancellable appendEntriesSchedule = null;
context.setCommitIndex(lastIndex());
}
- for (String followerId : context.getPeerAddresses().keySet()) {
+ followers = context.getPeerAddresses().keySet();
+
+ for (String followerId : followers) {
FollowerLogInformation followerLogInformation =
new FollowerLogInformationImpl(followerId,
new AtomicLong(lastIndex()),
new AtomicLong(-1));
- followerToActor.put(followerId,
- context.actorSelection(context.getPeerAddress(followerId)));
-
followerToLog.put(followerId, followerLogInformation);
}
- context.getLogger().debug("Election:Leader has following peers:"+followerToActor.keySet());
+ context.getLogger().debug("Election:Leader has following peers:"+ followers);
- if (followerToActor.size() > 0) {
- minReplicationCount = (followerToActor.size() + 1) / 2 + 1;
+ if (followers.size() > 0) {
+ minReplicationCount = (followers.size() + 1) / 2 + 1;
} else {
minReplicationCount = 0;
}
scheduleHeartBeat(new FiniteDuration(0, TimeUnit.SECONDS));
scheduleInstallSnapshotCheck(
- new FiniteDuration(HEART_BEAT_INTERVAL.length() * 1000,
- HEART_BEAT_INTERVAL.unit())
+ new FiniteDuration(context.getConfigParams().getHeartBeatInterval().length() * 1000,
+ context.getConfigParams().getHeartBeatInterval().unit())
);
}
@Override protected RaftState handleAppendEntries(ActorRef sender,
AppendEntries appendEntries) {
+ context.getLogger().info("Leader: Received {}", appendEntries.toString());
+
return state();
}
@Override protected RaftState handleAppendEntriesReply(ActorRef sender,
AppendEntriesReply appendEntriesReply) {
+ if(! appendEntriesReply.isSuccess()) {
+ context.getLogger()
+ .info("Leader: Received {}", appendEntriesReply.toString());
+ }
+
// Update the FollowerLogInformation
String followerId = appendEntriesReply.getFollowerId();
FollowerLogInformation followerLogInformation =
followerToLog.get(followerId);
+
+ if(followerLogInformation == null){
+ context.getLogger().error("Unknown follower {}", followerId);
+ return state();
+ }
+
if (appendEntriesReply.isSuccess()) {
followerLogInformation
.setMatchIndex(appendEntriesReply.getLogLastIndex());
(InstallSnapshotReply) message);
}
} finally {
- scheduleHeartBeat(HEART_BEAT_INTERVAL);
+ scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
}
return super.handleMessage(sender, message);
context.getLogger().debug("Replicate message " + logIndex);
- if (followerToActor.size() == 0) {
+ if (followers.size() == 0) {
context.setCommitIndex(
replicate.getReplicatedLogEntry().getIndex());
private void sendAppendEntries() {
// Send an AppendEntries to all followers
- for (String followerId : followerToActor.keySet()) {
+ for (String followerId : followers) {
ActorSelection followerActor =
- followerToActor.get(followerId);
+ context.getPeerActorSelection(followerId);
- FollowerLogInformation followerLogInformation =
- followerToLog.get(followerId);
+ if (followerActor != null) {
+ FollowerLogInformation followerLogInformation =
+ followerToLog.get(followerId);
- long nextIndex = followerLogInformation.getNextIndex().get();
+ long nextIndex = followerLogInformation.getNextIndex().get();
- List<ReplicatedLogEntry> entries = Collections.emptyList();
+ List<ReplicatedLogEntry> entries = Collections.emptyList();
- if(context.getReplicatedLog().isPresent(nextIndex)){
- // TODO: Instead of sending all entries from nextIndex
- // only send a fixed number of entries to each follower
- // This is to avoid the situation where there are a lot of
- // entries to install for a fresh follower or to a follower
- // that has fallen too far behind with the log but yet is not
- // eligible to receive a snapshot
- entries =
- context.getReplicatedLog().getFrom(nextIndex);
- }
+ if (context.getReplicatedLog().isPresent(nextIndex)) {
+ // TODO: Instead of sending all entries from nextIndex
+ // only send a fixed number of entries to each follower
+ // This is to avoid the situation where there are a lot of
+ // entries to install for a fresh follower or to a follower
+ // that has fallen too far behind with the log but yet is not
+ // eligible to receive a snapshot
+ entries =
+ context.getReplicatedLog().getFrom(nextIndex);
+ }
- followerActor.tell(
- new AppendEntries(currentTerm(), context.getId(), prevLogIndex(nextIndex),
- prevLogTerm(nextIndex), entries, context.getCommitIndex()).toSerializable(),
- actor());
+ followerActor.tell(
+ new AppendEntries(currentTerm(), context.getId(),
+ prevLogIndex(nextIndex),
+ prevLogTerm(nextIndex), entries,
+ context.getCommitIndex()).toSerializable(),
+ actor()
+ );
+ }
}
}
* snapshots at every heartbeat.
*/
private void installSnapshotIfNeeded(){
- for (String followerId : followerToActor.keySet()) {
+ for (String followerId : followers) {
ActorSelection followerActor =
- followerToActor.get(followerId);
-
- FollowerLogInformation followerLogInformation =
- followerToLog.get(followerId);
-
- long nextIndex = followerLogInformation.getNextIndex().get();
-
- if(!context.getReplicatedLog().isPresent(nextIndex) && context.getReplicatedLog().isInSnapshot(nextIndex)){
- followerActor.tell(
- new InstallSnapshot(currentTerm(), context.getId(),
- context.getReplicatedLog().getSnapshotIndex(),
- context.getReplicatedLog().getSnapshotTerm(),
- context.getReplicatedLog().getSnapshot()
- ),
- actor()
- );
+ context.getPeerActorSelection(followerId);
+
+ if(followerActor != null) {
+ FollowerLogInformation followerLogInformation =
+ followerToLog.get(followerId);
+
+ long nextIndex = followerLogInformation.getNextIndex().get();
+
+ if (!context.getReplicatedLog().isPresent(nextIndex) && context
+ .getReplicatedLog().isInSnapshot(nextIndex)) {
+ followerActor.tell(
+ new InstallSnapshot(currentTerm(), context.getId(),
+ context.getReplicatedLog().getSnapshotIndex(),
+ context.getReplicatedLog().getSnapshotTerm(),
+ context.getReplicatedLog().getSnapshot()
+ ),
+ actor()
+ );
+ }
}
}
}
private RaftState sendHeartBeat() {
- if (followerToActor.size() > 0) {
+ if (followers.size() > 0) {
sendAppendEntries();
}
return state();
}
private void scheduleHeartBeat(FiniteDuration interval) {
- if(followerToActor.keySet().size() == 0){
+ if(followers.size() == 0){
// Optimization - do not bother scheduling a heartbeat as there are
// no followers
return;
private void scheduleInstallSnapshotCheck(FiniteDuration interval) {
- if(followerToActor.keySet().size() == 0){
+ if(followers.size() == 0){
// Optimization - do not bother scheduling a heartbeat as there are
// no followers
return;
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
import org.opendaylight.controller.cluster.raft.protobuff.messages.AppendEntriesMessages;
-import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
* Invoked by leader to replicate log entries (§5.3); also used as
* heartbeat (§5.2).
*/
-public class AppendEntries extends AbstractRaftRPC implements Serializable {
+public class AppendEntries extends AbstractRaftRPC {
public static final Class SERIALIZABLE_CLASS = AppendEntriesMessages.AppendEntries.class;
}
@Override public String toString() {
- return "AppendEntries{" +
- "leaderId='" + leaderId + '\'' +
- ", prevLogIndex=" + prevLogIndex +
- ", prevLogTerm=" + prevLogTerm +
- ", entries=" + entries +
- ", leaderCommit=" + leaderCommit +
- '}';
+ final StringBuilder sb =
+ new StringBuilder("AppendEntries{");
+ sb.append("term=").append(getTerm());
+ sb.append("leaderId='").append(leaderId).append('\'');
+ sb.append(", prevLogIndex=").append(prevLogIndex);
+ sb.append(", prevLogTerm=").append(prevLogTerm);
+ sb.append(", entries=").append(entries);
+ sb.append(", leaderCommit=").append(leaderCommit);
+ sb.append('}');
+ return sb.toString();
}
public <T extends Object> Object toSerializable(){
package org.opendaylight.controller.cluster.raft.messages;
-import java.io.Serializable;
-
/**
* Reply for the AppendEntriesRpc message
*/
-public class AppendEntriesReply extends AbstractRaftRPC implements Serializable {
+public class AppendEntriesReply extends AbstractRaftRPC {
// true if follower contained entry matching
// prevLogIndex and prevLogTerm
public String getFollowerId() {
return followerId;
}
+
+ @Override public String toString() {
+ final StringBuilder sb =
+ new StringBuilder("AppendEntriesReply{");
+ sb.append("term=").append(term);
+ sb.append(", success=").append(success);
+ sb.append(", logLastIndex=").append(logLastIndex);
+ sb.append(", logLastTerm=").append(logLastTerm);
+ sb.append(", followerId='").append(followerId).append('\'');
+ sb.append('}');
+ return sb.toString();
+ }
}
package org.opendaylight.controller.cluster.raft.messages;
-import java.io.Serializable;
-
-public class InstallSnapshot extends AbstractRaftRPC implements Serializable {
+public class InstallSnapshot extends AbstractRaftRPC {
private final String leaderId;
private final long lastIncludedIndex;
package org.opendaylight.controller.cluster.raft.messages;
-import java.io.Serializable;
-
-public class InstallSnapshotReply extends AbstractRaftRPC implements Serializable {
+public class InstallSnapshotReply extends AbstractRaftRPC {
// The followerId - this will be used to figure out which follower is
// responding
package org.opendaylight.controller.cluster.raft.messages;
-public interface RaftRPC {
+import java.io.Serializable;
+
+public interface RaftRPC extends Serializable {
public long getTerm();
}
package org.opendaylight.controller.cluster.raft.messages;
-import java.io.Serializable;
-
/**
* Invoked by candidates to gather votes (§5.2).
*/
-public class RequestVote extends AbstractRaftRPC implements Serializable{
+public class RequestVote extends AbstractRaftRPC {
// candidate requesting vote
private String candidateId;
public void setLastLogTerm(long lastLogTerm) {
this.lastLogTerm = lastLogTerm;
}
+
+ @Override public String toString() {
+ final StringBuilder sb =
+ new StringBuilder("RequestVote{");
+ sb.append("term='").append(getTerm()).append('\'');
+ sb.append("candidateId='").append(candidateId).append('\'');
+ sb.append(", lastLogIndex=").append(lastLogIndex);
+ sb.append(", lastLogTerm=").append(lastLogTerm);
+ sb.append('}');
+ return sb.toString();
+ }
}
package org.opendaylight.controller.cluster.raft.messages;
-import java.io.Serializable;
-
-public class RequestVoteReply extends AbstractRaftRPC implements Serializable {
+public class RequestVoteReply extends AbstractRaftRPC {
// true means candidate received vot
private final boolean voteGranted;
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.raft;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
+import static org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockReplicatedLogEntry;
+/**
+*
+*/
+public class AbstractReplicatedLogImplTest {
+
+ private MockAbstractReplicatedLogImpl replicatedLogImpl;
+
+ @Before
+ public void setUp() {
+ replicatedLogImpl = new MockAbstractReplicatedLogImpl();
+ }
+
+ @After
+ public void tearDown() {
+ replicatedLogImpl.journal.clear();
+ replicatedLogImpl.setSnapshotIndex(-1);
+ replicatedLogImpl.setSnapshotTerm(-1);
+ replicatedLogImpl = null;
+ }
+
+ @Test
+ public void testIndexOperations() {
+ // create a set of initial entries in the in-memory log
+ replicatedLogImpl.append(new MockReplicatedLogEntry(1, 0, new MockPayload("A")));
+ replicatedLogImpl.append(new MockReplicatedLogEntry(1, 1, new MockPayload("B")));
+ replicatedLogImpl.append(new MockReplicatedLogEntry(1, 2, new MockPayload("C")));
+ replicatedLogImpl.append(new MockReplicatedLogEntry(2, 3, new MockPayload("D")));
+
+ // check if the values returned are correct, with snapshotIndex = -1
+ assertEquals("B", replicatedLogImpl.get(1).getData().toString());
+ assertEquals("D", replicatedLogImpl.last().getData().toString());
+ assertEquals(3, replicatedLogImpl.lastIndex());
+ assertEquals(2, replicatedLogImpl.lastTerm());
+ assertEquals(2, replicatedLogImpl.getFrom(2).size());
+ assertEquals(4, replicatedLogImpl.size());
+ assertTrue(replicatedLogImpl.isPresent(2));
+ assertFalse(replicatedLogImpl.isPresent(4));
+ assertFalse(replicatedLogImpl.isInSnapshot(2));
+
+ // now create a snapshot of 3 entries, with 1 unapplied entry left in the log
+ // It removes the entries which have made it to snapshot
+ // and updates the snapshot index and term
+ Map state = takeSnapshot(3);
+
+ // check the values after the snapshot.
+ // each index value passed in the test is the logical index (log entry index)
+ // which gets mapped to the list's physical index
+ assertEquals("D", replicatedLogImpl.get(3).getData().toString());
+ assertEquals("D", replicatedLogImpl.last().getData().toString());
+ assertNull(replicatedLogImpl.get(1));
+ assertEquals(3, replicatedLogImpl.lastIndex());
+ assertEquals(2, replicatedLogImpl.lastTerm());
+ assertEquals(0, replicatedLogImpl.getFrom(2).size());
+ assertEquals(1, replicatedLogImpl.size());
+ assertFalse(replicatedLogImpl.isPresent(2));
+ assertTrue(replicatedLogImpl.isPresent(3));
+ assertFalse(replicatedLogImpl.isPresent(4));
+ assertTrue(replicatedLogImpl.isInSnapshot(2));
+
+ // append few more entries
+ replicatedLogImpl.append(new MockReplicatedLogEntry(2, 4, new MockPayload("E")));
+ replicatedLogImpl.append(new MockReplicatedLogEntry(2, 5, new MockPayload("F")));
+ replicatedLogImpl.append(new MockReplicatedLogEntry(3, 6, new MockPayload("G")));
+ replicatedLogImpl.append(new MockReplicatedLogEntry(3, 7, new MockPayload("H")));
+
+ // check their values as well
+ assertEquals(5, replicatedLogImpl.size());
+ assertEquals("D", replicatedLogImpl.get(3).getData().toString());
+ assertEquals("E", replicatedLogImpl.get(4).getData().toString());
+ assertEquals("H", replicatedLogImpl.last().getData().toString());
+ assertEquals(3, replicatedLogImpl.lastTerm());
+ assertEquals(7, replicatedLogImpl.lastIndex());
+ assertTrue(replicatedLogImpl.isPresent(7));
+ assertFalse(replicatedLogImpl.isInSnapshot(7));
+ assertEquals(1, replicatedLogImpl.getFrom(7).size());
+ assertEquals(2, replicatedLogImpl.getFrom(6).size());
+
+ // take a second snapshot with 5 entries with 0 unapplied entries left in the log
+ state = takeSnapshot(5);
+
+ assertEquals(0, replicatedLogImpl.size());
+ assertNull(replicatedLogImpl.last());
+ assertNull(replicatedLogImpl.get(7));
+ assertNull(replicatedLogImpl.get(1));
+ assertFalse(replicatedLogImpl.isPresent(7));
+ assertTrue(replicatedLogImpl.isInSnapshot(7));
+ assertEquals(0, replicatedLogImpl.getFrom(7).size());
+ assertEquals(0, replicatedLogImpl.getFrom(6).size());
+
+ }
+
+ // create a snapshot for test
+ public Map takeSnapshot(int numEntries) {
+ Map map = new HashMap(numEntries);
+ List<ReplicatedLogEntry> entries = replicatedLogImpl.getEntriesTill(numEntries);
+ for (ReplicatedLogEntry entry : entries) {
+ map.put(entry.getIndex(), entry.getData().toString());
+ }
+
+ int term = (int) replicatedLogImpl.lastTerm();
+ int lastIndex = (int) entries.get(entries.size() - 1).getIndex();
+ entries.clear();
+ replicatedLogImpl.setSnapshotTerm(term);
+ replicatedLogImpl.setSnapshotIndex(lastIndex);
+
+ return map;
+
+ }
+ class MockAbstractReplicatedLogImpl extends AbstractReplicatedLogImpl {
+ @Override
+ public void appendAndPersist(ReplicatedLogEntry replicatedLogEntry) {
+ }
+
+ @Override
+ public void removeFromAndPersist(long index) {
+ }
+
+ public void setSnapshotIndex(long snapshotIndex) {
+ this.snapshotIndex = snapshotIndex;
+ }
+
+ public void setSnapshotTerm(long snapshotTerm) {
+ this.snapshotTerm = snapshotTerm;
+ }
+
+ public List<ReplicatedLogEntry> getEntriesTill(int index) {
+ return journal.subList(0, index);
+ }
+ }
+}
import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
import org.opendaylight.controller.cluster.raft.protobuff.messages.AppendEntriesMessages;
import org.opendaylight.controller.cluster.raft.protobuff.messages.MockPayloadMessages;
+import com.google.common.base.Preconditions;
import java.io.Serializable;
import java.util.ArrayList;
peerAddresses.remove(name);
}
+ @Override public ActorSelection getPeerActorSelection(String peerId) {
+ String peerAddress = getPeerAddress(peerId);
+ if(peerAddress != null){
+ return actorSelection(peerAddress);
+ }
+ return null;
+ }
+
+ @Override public void setPeerAddress(String peerId, String peerAddress) {
+ Preconditions.checkState(peerAddresses.containsKey(peerId));
+ peerAddresses.put(peerId, peerAddress);
+ }
+
public void setPeerAddresses(Map<String, String> peerAddresses) {
this.peerAddresses = peerAddresses;
}
-
+ @Override
+ public ConfigParams getConfigParams() {
+ return new DefaultConfigParamsImpl();
+ }
public static class SimpleReplicatedLog implements ReplicatedLog {
private final List<ReplicatedLogEntry> log = new ArrayList<>();
import org.opendaylight.controller.cluster.raft.MockRaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
-import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
+import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
import org.opendaylight.controller.cluster.raft.messages.RequestVote;
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
-import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
+import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
import org.opendaylight.controller.cluster.raft.messages.RequestVote;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
-import org.opendaylight.controller.cluster.raft.internal.messages.ApplyState;
-import org.opendaylight.controller.cluster.raft.internal.messages.Replicate;
-import org.opendaylight.controller.cluster.raft.internal.messages.SendHeartBeat;
+import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
+import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
+import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
}
final RuntimeGeneratedMappingServiceImpl service = new RuntimeGeneratedMappingServiceImpl(SingletonHolder.CLASS_POOL);
- bundleContext.registerService(SchemaServiceListener.class, service, new Hashtable<String,String>());
+ bundleContext.registerService(SchemaContextListener.class, service, new Hashtable<String,String>());
return service;
}
import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final BindingToNormalizedNodeCodec codec;
private BindingIndependentConnector connector;
private ProviderSession context;
- private final ListenerRegistration<SchemaServiceListener> schemaListenerRegistration;
+ private final ListenerRegistration<SchemaContextListener> schemaListenerRegistration;
protected AbstractForwardedDataBroker(final DOMDataBroker domDataBroker,
final BindingIndependentMappingService mappingService,final SchemaService schemaService) {
this.domDataBroker = domDataBroker;
this.mappingService = mappingService;
this.codec = new BindingToNormalizedNodeCodec(mappingService);
- this.schemaListenerRegistration = schemaService.registerSchemaServiceListener(this);
+ this.schemaListenerRegistration = schemaService.registerSchemaContextListener(this);
}
protected BindingToNormalizedNodeCodec getCodec() {
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.Executors;
import org.opendaylight.controller.md.sal.binding.util.AbstractBindingSalProviderInstance;
import org.opendaylight.controller.sal.binding.api.mount.MountProviderInstance;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
public class MountPointManagerImpl implements MountProviderService {
RpcProviderRegistryImpl rpcRegistry = new RpcProviderRegistryImpl("mount");
NotificationBrokerImpl notificationBroker = new NotificationBrokerImpl(getNotificationExecutor());
DataBrokerImpl dataBroker = new DataBrokerImpl();
- dataBroker.setExecutor(getDataCommitExecutor());
+ dataBroker.setExecutor(MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
BindingMountPointImpl mountInstance = new BindingMountPointImpl(path, rpcRegistry, notificationBroker,
dataBroker);
mountPoints.putIfAbsent(path, mountInstance);
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.impl.test;
+
+import static org.opendaylight.controller.md.sal.binding.test.AssertCollections.assertContains;
+import static org.opendaylight.controller.md.sal.binding.test.AssertCollections.assertEmpty;
+import static org.opendaylight.controller.md.sal.binding.test.AssertCollections.assertNotContains;
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.TOP_FOO_KEY;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.USES_ONE_KEY;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.USES_TWO_KEY;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.complexUsesAugment;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.path;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.top;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.topLevelList;
+
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.binding.test.AbstractDataChangeListenerTest;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugment;
+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.list.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+/**
+ *
+ * This testsuite tries to replicate bug 1333 and tests regresion of it
+ * using test-model with similar construction as one reported.
+ *
+ *
+ * See https://bugs.opendaylight.org/show_bug.cgi?id=1333 for Bug Description
+ *
+ */
+public class Bug1333DataChangeListenerTest extends AbstractDataChangeListenerTest{
+
+ private static final InstanceIdentifier<Top> TOP_PATH = InstanceIdentifier.create(Top.class);
+
+ private static final InstanceIdentifier<?> AUGMENT_WILDCARD = TOP_PATH.child(TopLevelList.class).augmentation(
+ TreeComplexUsesAugment.class);
+
+ public void writeTopWithListItem(final LogicalDatastoreType store) {
+ ReadWriteTransaction tx = getDataBroker().newReadWriteTransaction();
+ Top topItem = top(topLevelList(TOP_FOO_KEY, complexUsesAugment(USES_ONE_KEY, USES_TWO_KEY)));
+ tx.put(store, TOP_PATH, topItem);
+ assertCommit(tx.submit());
+ }
+
+ public void deleteItem(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
+ ReadWriteTransaction tx = getDataBroker().newReadWriteTransaction();
+ tx.delete(store, path);
+ assertCommit(tx.submit());
+ }
+
+ @Test
+ public void writeTopWithListItemAugmentedListenTopSubtree() {
+ TestListener listener = createListener(CONFIGURATION,TOP_PATH, DataChangeScope.SUBTREE);
+ listener.startCapture();
+
+ writeTopWithListItem(CONFIGURATION);
+
+ AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = listener.event();
+
+ assertContains(event.getCreatedData(), TOP_PATH);
+ assertContains(event.getCreatedData(), path(TOP_FOO_KEY));
+ assertContains(event.getCreatedData(), path(TOP_FOO_KEY, TreeComplexUsesAugment.class));
+ assertContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_ONE_KEY));
+ assertContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_TWO_KEY));
+
+ assertEmpty(event.getUpdatedData());
+ assertEmpty(event.getRemovedPaths());
+ }
+
+ @Test
+ public void writeTopWithListItemAugmentedListenAugmentSubtreeWildcarded() {
+ TestListener listener = createListener(CONFIGURATION,AUGMENT_WILDCARD, DataChangeScope.SUBTREE);
+ listener.startCapture();
+ writeTopWithListItem(CONFIGURATION);
+
+ AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = listener.event();
+
+ /*
+ * Event should not contain parent nodes
+ */
+ assertNotContains(event.getCreatedData(), TOP_PATH, path(TOP_FOO_KEY));
+
+ assertContains(event.getCreatedData(), path(TOP_FOO_KEY, TreeComplexUsesAugment.class));
+ assertContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_ONE_KEY));
+ assertContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_TWO_KEY));
+
+ assertEmpty(event.getUpdatedData());
+ assertEmpty(event.getRemovedPaths());
+ }
+
+ @Test
+ public void deleteAugmentChildListenTopSubtree() {
+ writeTopWithListItem(CONFIGURATION);
+ TestListener listener = createListener(CONFIGURATION, TOP_PATH, DataChangeScope.SUBTREE);
+ InstanceIdentifier<?> deletePath = path(TOP_FOO_KEY,USES_ONE_KEY);
+ deleteItem(CONFIGURATION,deletePath);
+
+ AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = listener.event();
+
+
+ assertEmpty(event.getCreatedData());
+
+ assertContains(event.getRemovedPaths(), deletePath);
+
+ assertContains(event.getUpdatedData(), TOP_PATH);
+ assertContains(event.getUpdatedData(), path(TOP_FOO_KEY));
+ assertContains(event.getUpdatedData(), path(TOP_FOO_KEY, TreeComplexUsesAugment.class));
+
+ assertNotContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_TWO_KEY));
+ }
+
+ @Test
+ public void deleteAugmentChildListenAugmentSubtreeWildcarded() {
+ writeTopWithListItem(CONFIGURATION);
+
+ TestListener listener = createListener(CONFIGURATION, AUGMENT_WILDCARD, DataChangeScope.SUBTREE);
+ InstanceIdentifier<?> deletePath = path(TOP_FOO_KEY,USES_ONE_KEY);
+ deleteItem(CONFIGURATION,deletePath);
+ AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = listener.event();
+
+ assertEmpty(event.getCreatedData());
+
+ assertContains(event.getUpdatedData(), path(TOP_FOO_KEY, TreeComplexUsesAugment.class));
+
+ /*
+ * Event should not contain parent nodes
+ */
+ assertNotContains(event.getUpdatedData(), TOP_PATH, path(TOP_FOO_KEY));
+
+ assertContains(event.getRemovedPaths(), deletePath);
+ }
+
+}
public DOMStore createConfigurationDatastore() {
InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
- schemaService.registerSchemaServiceListener(store);
+ schemaService.registerSchemaContextListener(store);
return store;
}
public DOMStore createOperationalDatastore() {
InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
- schemaService.registerSchemaServiceListener(store);
+ schemaService.registerSchemaContextListener(store);
return store;
}
biCompatibleBroker = new BackwardsCompatibleDataBroker(newDOMDataBroker,mockSchemaService);
- mockSchemaService.registerSchemaServiceListener(configStore);
- mockSchemaService.registerSchemaServiceListener(operStore);
+ mockSchemaService.registerSchemaContextListener(configStore);
+ mockSchemaService.registerSchemaContextListener(operStore);
biDataLegacyBroker = biCompatibleBroker;
}
public void startBindingToDomMappingService() {
checkState(classPool != null, "ClassPool needs to be present");
mappingServiceImpl = new RuntimeGeneratedMappingServiceImpl(classPool);
- mockSchemaService.registerSchemaServiceListener(mappingServiceImpl);
+ mockSchemaService.registerSchemaContextListener(mappingServiceImpl);
}
private void updateYangSchema(final ImmutableSet<YangModuleInfo> moduleInfos) {
import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
@SuppressWarnings("deprecation")
public final class MockSchemaService implements SchemaService, SchemaContextProvider {
private SchemaContext schemaContext;
- ListenerRegistry<SchemaServiceListener> listeners = ListenerRegistry.create();
+ ListenerRegistry<SchemaContextListener> listeners = ListenerRegistry.create();
@Override
public void addModule(final Module module) {
}
@Override
- public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(
- final SchemaServiceListener listener) {
+ public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
+ final SchemaContextListener listener) {
return listeners.register(listener);
}
public synchronized void changeSchema(final SchemaContext newContext) {
schemaContext = newContext;
- for (ListenerRegistration<SchemaServiceListener> listener : listeners) {
+ for (ListenerRegistration<SchemaContextListener> listener : listeners) {
listener.getInstance().onGlobalContextUpdated(schemaContext);
}
}
-}
\ No newline at end of file
+}
<version>1.1-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft</artifactId>
+ <version>1.1-SNAPSHOT</version>
+ </dependency>
+
<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<Import-Package>!*snappy;!org.jboss.*;*</Import-Package>
<Embed-Dependency>
sal-protocolbuffer-encoding;
+ sal-akka-raft;
!sal*;
!*config-api*;
!*testkit*;
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import com.google.common.base.Preconditions;
+import com.google.protobuf.GeneratedMessage;
+import org.opendaylight.controller.cluster.example.protobuff.messages.KeyValueMessages;
+import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
+import org.opendaylight.controller.cluster.raft.protobuff.messages.AppendEntriesMessages;
+import org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+public class CompositeModificationPayload extends Payload implements
+ Serializable {
+
+ private final PersistentMessages.CompositeModification modification;
+
+ public CompositeModificationPayload(){
+ modification = null;
+ }
+ public CompositeModificationPayload(Object modification){
+ this.modification = (PersistentMessages.CompositeModification) modification;
+ }
+
+ @Override public Map<GeneratedMessage.GeneratedExtension, PersistentMessages.CompositeModification> encode() {
+ Preconditions.checkState(modification!=null);
+ Map<GeneratedMessage.GeneratedExtension, PersistentMessages.CompositeModification> map = new HashMap<>();
+ map.put(org.opendaylight.controller.mdsal.CompositeModificationPayload.modification, this.modification);
+ return map;
+ }
+
+ @Override public Payload decode(
+ AppendEntriesMessages.AppendEntries.ReplicatedLogEntry.Payload payload) {
+ PersistentMessages.CompositeModification modification = payload
+ .getExtension(
+ org.opendaylight.controller.mdsal.CompositeModificationPayload.modification);
+ payload.getExtension(KeyValueMessages.value);
+ return new CompositeModificationPayload(modification);
+ }
+
+ public Object getModification(){
+ return this.modification;
+ }
+}
import java.util.Map;
public interface Configuration {
+
+ /**
+ * Given a memberName find all the shards that belong on that member and
+ * return the names of those shards
+ *
+ * @param memberName
+ * @return
+ */
List<String> getMemberShardNames(String memberName);
+
+ /**
+ * Given a module namespace return the name of a module
+ * @param nameSpace
+ * @return
+ */
Optional<String> getModuleNameFromNameSpace(String nameSpace);
+
+ /**
+ * Get a mapping of the module names to it's corresponding ShardStrategy
+ * @return
+ */
Map<String, ShardStrategy> getModuleNameToShardStrategyMap();
+
+ /**
+ * Given a module name find all the shardNames corresponding to it
+ * @param moduleName
+ * @return
+ */
List<String> getShardNamesFromModuleName(String moduleName);
+
+ /**
+ * Given a shardName find all the members on which it belongs
+ *
+ * @param shardName
+ * @return
+ */
List<String> getMembersFromShardName(String shardName);
}
new DistributedDataStore(actorSystem, name, new ClusterWrapperImpl(actorSystem),config );
ShardStrategyFactory.setConfiguration(config);
schemaService
- .registerSchemaServiceListener(dataStore);
+ .registerSchemaContextListener(dataStore);
return dataStore;
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.UntypedActor;
+import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransactionReply;
+
+public class NoOpCohort extends UntypedActor {
+
+ @Override public void onReceive(Object message) throws Exception {
+ if (message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
+ getSender().tell(new CanCommitTransactionReply(false).toSerializable(), getSelf());
+ } else if (message.getClass().equals(PreCommitTransaction.SERIALIZABLE_CLASS)) {
+ getSender().tell(
+ new PreCommitTransactionReply().toSerializable(),
+ getSelf());
+ } else if (message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
+ getSender().tell(new CommitTransactionReply().toSerializable(), getSelf());
+ } else if (message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
+ getSender().tell(new AbortTransactionReply().toSerializable(), getSelf());
+ } else {
+ throw new Exception ("Not recognized message received,message="+message);
+ }
+
+ }
+}
+
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.Creator;
-import akka.persistence.Persistent;
-import akka.persistence.RecoveryCompleted;
-import akka.persistence.UntypedProcessor;
+import akka.serialization.Serialization;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChainReply;
import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
import org.opendaylight.controller.cluster.datastore.messages.ForwardedCommitTransaction;
-import org.opendaylight.controller.cluster.datastore.messages.NonPersistent;
+import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
import org.opendaylight.controller.cluster.datastore.modification.Modification;
import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
+import org.opendaylight.controller.cluster.raft.RaftActor;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
* Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
* </p>
*/
-public class Shard extends UntypedProcessor {
+public class Shard extends RaftActor {
public static final String DEFAULT_NAME = "default";
// property persistent
private final boolean persistent;
+ private final String name;
+
private SchemaContext schemaContext;
private final ShardStats shardMBean;
- private Shard(String name) {
+ private Shard(String name, Map<String, String> peerAddresses) {
+ super(name, peerAddresses);
+
+ this.name = name;
String setting = System.getProperty("shard.persistent");
}
- public static Props props(final String name) {
+ public static Props props(final String name, final Map<String, String> peerAddresses) {
return Props.create(new Creator<Shard>() {
@Override
public Shard create() throws Exception {
- return new Shard(name);
+ return new Shard(name, peerAddresses);
}
});
}
- @Override
- public void onReceive(Object message) throws Exception {
- LOG.debug("Received message " + message.getClass().toString());
-
- if(!recoveryFinished()){
- // FIXME : Properly handle recovery
- return;
- }
+ @Override public void onReceiveCommand(Object message){
+ LOG.debug("Received message {} from {}", message.getClass().toString(), getSender());
if (message.getClass().equals(CreateTransactionChain.SERIALIZABLE_CLASS)) {
- createTransactionChain();
+ if(isLeader()) {
+ createTransactionChain();
+ } else if(getLeader() != null){
+ getLeader().forward(message, getContext());
+ }
} else if (message.getClass().equals(RegisterChangeListener.SERIALIZABLE_CLASS)) {
registerChangeListener(RegisterChangeListener.fromSerializable(getContext().system(), message));
} else if (message instanceof UpdateSchemaContext) {
updateSchemaContext((UpdateSchemaContext) message);
} else if (message instanceof ForwardedCommitTransaction) {
handleForwardedCommit((ForwardedCommitTransaction) message);
- } else if (message instanceof Persistent) {
- commit(((Persistent)message).payload());
} else if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
- createTransaction(CreateTransaction.fromSerializable(message));
- } else if(message instanceof NonPersistent){
- commit(((NonPersistent)message).payload());
- }else if (message instanceof RecoveryCompleted) {
- //FIXME: PROPERLY HANDLE RECOVERY COMPLETED
-
- }else {
- throw new Exception("Not recognized message found message=" + message);
+ if(isLeader()) {
+ createTransaction(CreateTransaction.fromSerializable(message));
+ } else if(getLeader() != null){
+ getLeader().forward(message, getContext());
+ }
+ } else if (message instanceof PeerAddressResolved){
+ PeerAddressResolved resolved = (PeerAddressResolved) message;
+ setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
+ } else {
+ super.onReceiveCommand(message);
}
}
private void createTransaction(CreateTransaction createTransaction) {
DOMStoreReadWriteTransaction transaction =
store.newReadWriteTransaction();
+ String transactionId = "shard-" + createTransaction.getTransactionId();
+ LOG.info("Creating transaction : {} " , transactionId);
ActorRef transactionActor = getContext().actorOf(
- ShardTransaction.props(transaction, getSelf(), schemaContext), "shard-" + createTransaction.getTransactionId());
+ ShardTransaction.props(transaction, getSelf(), schemaContext), transactionId);
+
getSender()
- .tell(new CreateTransactionReply(transactionActor.path().toString(), createTransaction.getTransactionId()).toSerializable(),
+ .tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor), createTransaction.getTransactionId()).toSerializable(),
getSelf());
}
- private void commit(Object serialized) {
+ private void commit(final ActorRef sender, Object serialized) {
Modification modification = MutableCompositeModification.fromSerializable(serialized, schemaContext);
DOMStoreThreePhaseCommitCohort cohort =
modificationToCohort.remove(serialized);
if (cohort == null) {
LOG.error(
"Could not find cohort for modification : " + modification);
+ LOG.info("Writing modification using a new transaction");
+ modification.apply(store.newReadWriteTransaction());
return;
}
+
final ListenableFuture<Void> future = cohort.commit();
shardMBean.incrementCommittedTransactionCount();
- final ActorRef sender = getSender();
final ActorRef self = getSelf();
future.addListener(new Runnable() {
@Override
public void run() {
try {
future.get();
- sender.tell(new CommitTransactionReply().toSerializable(), self);
+
+ if(sender != null) {
+ sender
+ .tell(new CommitTransactionReply().toSerializable(),
+ self);
+ } else {
+ LOG.error("sender is null ???");
+ }
} catch (InterruptedException | ExecutionException e) {
// FIXME : Handle this properly
LOG.error(e, "An exception happened when committing");
modificationToCohort
.put(serializedModification , message.getCohort());
+
if(persistent) {
- getSelf().forward(Persistent.create(serializedModification),
- getContext());
+ this.persistData(getSender(), "identifier", new CompositeModificationPayload(serializedModification));
} else {
- getSelf().forward(NonPersistent.create(serializedModification),
- getContext());
+ this.commit(getSender(), serializedModification);
}
}
ActorSelection dataChangeListenerPath = getContext()
- .system().actorSelection(registerChangeListener.getDataChangeListenerPath());
+ .system().actorSelection(
+ registerChangeListener.getDataChangeListenerPath());
AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>
listener = new DataChangeListenerProxy(schemaContext,dataChangeListenerPath);
private void createTransactionChain() {
DOMStoreTransactionChain chain = store.createTransactionChain();
ActorRef transactionChain =
- getContext().actorOf(ShardTransactionChain.props(chain, schemaContext));
+ getContext().actorOf(
+ ShardTransactionChain.props(chain, schemaContext));
getSender()
- .tell(new CreateTransactionChainReply(transactionChain.path()).toSerializable(),
+ .tell(new CreateTransactionChainReply(transactionChain.path())
+ .toSerializable(),
getSelf());
}
+
+ @Override protected void applyState(ActorRef clientActor, String identifier,
+ Object data) {
+
+ if(data instanceof CompositeModificationPayload){
+ Object modification =
+ ((CompositeModificationPayload) data).getModification();
+ commit(clientActor, modification);
+ } else {
+ LOG.error("Unknown state received {}", data);
+ }
+
+ }
+
+ @Override protected Object createSnapshot() {
+ throw new UnsupportedOperationException("createSnapshot");
+ }
+
+ @Override protected void applySnapshot(Object snapshot) {
+ throw new UnsupportedOperationException("applySnapshot");
+ }
+
+ @Override public String persistenceId() {
+ return this.name;
+ }
}
import akka.japi.Function;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
+import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
// Stores a mapping between a member name and the address of the member
private final Map<String, Address> memberNameToAddress = new HashMap<>();
- private final Map<String, ActorPath> localShards = new HashMap<>();
+ private final Map<String, ShardInformation> localShards = new HashMap<>();
private final String type;
}
private void memberUp(ClusterEvent.MemberUp message) {
- memberNameToAddress.put(message.member().roles().head(), message.member().address());
+ String memberName = message.member().roles().head();
+
+ memberNameToAddress.put(memberName , message.member().address());
+
+ for(ShardInformation info : localShards.values()){
+ String shardName = info.getShardName();
+ info.updatePeerAddress(getShardActorName(memberName, shardName),
+ getShardActorPath(shardName, memberName));
+ }
}
private void updateSchemaContext(Object message) {
- for(ActorPath path : localShards.values()){
- getContext().system().actorSelection(path)
- .forward(message,
- getContext());
+ for(ShardInformation info : localShards.values()){
+ info.getActor().tell(message,getSelf());
}
}
List<String> members =
configuration.getMembersFromShardName(shardName);
- for(String memberName : members) {
- if (memberName.equals(cluster.getCurrentMemberName())) {
- // This is a local shard
- ActorPath shardPath = localShards.get(shardName);
- if (shardPath == null) {
- getSender()
- .tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
- return;
- }
- getSender().tell(new PrimaryFound(shardPath.toString()).toSerializable(),
- getSelf());
+ // First see if the there is a local replica for the shard
+ ShardInformation info = localShards.get(shardName);
+ if(info != null) {
+ ActorPath shardPath = info.getActorPath();
+ if (shardPath != null) {
+ getSender()
+ .tell(
+ new PrimaryFound(shardPath.toString()).toSerializable(),
+ getSelf());
return;
- } else {
- Address address = memberNameToAddress.get(memberName);
- if(address != null){
- String path =
- address.toString() + "/user/shardmanager-" + this.type + "/" + getShardActorName(
- memberName, shardName);
- getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
- return;
- }
+ }
+ }
+ if(cluster.getCurrentMemberName() != null) {
+ members.remove(cluster.getCurrentMemberName());
+ }
+ // There is no way for us to figure out the primary (for now) so assume
+ // that one of the remote nodes is a primary
+ for(String memberName : members) {
+ Address address = memberNameToAddress.get(memberName);
+ if(address != null){
+ String path =
+ getShardActorPath(shardName, memberName);
+ getSender().tell(new PrimaryFound(path).toSerializable(), getSelf());
+ return;
}
}
-
getSender().tell(new PrimaryNotFound(shardName).toSerializable(), getSelf());
}
+ private String
+
+
+ getShardActorPath(String shardName, String memberName) {
+ Address address = memberNameToAddress.get(memberName);
+ if(address != null) {
+ return address.toString() + "/user/shardmanager-" + this.type + "/"
+ + getShardActorName(
+ memberName, shardName);
+ }
+ return null;
+ }
+
private String getShardActorName(String memberName, String shardName){
return memberName + "-shard-" + shardName + "-" + this.type;
}
for(String shardName : memberShardNames){
String shardActorName = getShardActorName(memberName, shardName);
+ Map<String, String> peerAddresses = getPeerAddresses(shardName);
ActorRef actor = getContext()
- .actorOf(Shard.props(shardActorName), shardActorName);
- ActorPath path = actor.path();
- localShards.put(shardName, path);
+ .actorOf(Shard.props(shardActorName, peerAddresses),
+ shardActorName);
+ localShards.put(shardName, new ShardInformation(shardName, actor, peerAddresses));
}
}
+ private Map<String, String> getPeerAddresses(String shardName){
+
+ Map<String, String> peerAddresses = new HashMap<>();
+
+ List<String> members =
+ this.configuration.getMembersFromShardName(shardName);
+
+ String currentMemberName = this.cluster.getCurrentMemberName();
+
+ for(String memberName : members){
+ if(!currentMemberName.equals(memberName)){
+ String shardActorName = getShardActorName(memberName, shardName);
+ String path =
+ getShardActorPath(shardName, currentMemberName);
+ peerAddresses.put(shardActorName, path);
+ }
+ }
+ return peerAddresses;
+ }
+
@Override
public SupervisorStrategy supervisorStrategy() {
);
}
+
+ private class ShardInformation {
+ private final String shardName;
+ private final ActorRef actor;
+ private final ActorPath actorPath;
+ private final Map<String, String> peerAddresses;
+
+ private ShardInformation(String shardName, ActorRef actor,
+ Map<String, String> peerAddresses) {
+ this.shardName = shardName;
+ this.actor = actor;
+ this.actorPath = actor.path();
+ this.peerAddresses = peerAddresses;
+ }
+
+ public String getShardName() {
+ return shardName;
+ }
+
+ public ActorRef getActor(){
+ return actor;
+ }
+
+ public ActorPath getActorPath() {
+ return actorPath;
+ }
+
+ public Map<String, String> getPeerAddresses() {
+ return peerAddresses;
+ }
+
+ public void updatePeerAddress(String peerId, String peerAddress){
+ LOG.info("updatePeerAddress for peer {} with address {}", peerId, peerAddress);
+ if(peerAddresses.containsKey(peerId)){
+ peerAddresses.put(peerId, peerAddress);
+
+ LOG.info("Sending PeerAddressResolved for peer {} with address {} to {}", peerId, peerAddress, actor.path());
+
+ actor
+ .tell(new PeerAddressResolved(peerId, peerAddress),
+ getSelf());
+
+ }
+ }
+ }
}
package org.opendaylight.controller.cluster.datastore;
import akka.actor.ActorPath;
+import akka.actor.ActorRef;
import akka.actor.ActorSelection;
+import akka.actor.Props;
import com.google.common.base.Optional;
+import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
+import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException;
import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
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 java.util.ArrayList;
import java.util.HashMap;
private static final AtomicLong counter = new AtomicLong();
+ private static final Logger
+ LOG = LoggerFactory.getLogger(TransactionProxy.class);
+
+
private final TransactionType transactionType;
private final ActorContext actorContext;
private final Map<String, TransactionContext> remoteTransactionPaths = new HashMap<>();
TransactionType transactionType,
ExecutorService executor,
SchemaContext schemaContext
- ) {
+ ) {
this.identifier = actorContext.getCurrentMemberName() + "-txn-" + counter.getAndIncrement();
this.transactionType = transactionType;
createTransactionIfMissing(actorContext, path);
- final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
-
- Callable<Optional<NormalizedNode<?,?>>> call = new Callable() {
-
- @Override public Optional<NormalizedNode<?,?>> call() throws Exception {
- Object response = actorContext
- .executeRemoteOperation(remoteTransaction, new ReadData(path).toSerializable(),
- ActorContext.ASK_DURATION);
- if(response.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)){
- ReadDataReply reply = ReadDataReply.fromSerializable(schemaContext,path, response);
- if(reply.getNormalizedNode() == null){
- return Optional.absent();
- }
- //FIXME : A cast should not be required here ???
- return (Optional<NormalizedNode<?, ?>>) Optional.of(reply.getNormalizedNode());
- }
-
- return Optional.absent();
- }
- };
-
- ListenableFutureTask<Optional<NormalizedNode<?, ?>>>
- future = ListenableFutureTask.create(call);
-
- executor.submit(future);
-
- return future;
+ return transactionContext(path).readData(path);
}
@Override
createTransactionIfMissing(actorContext, path);
- final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
- remoteTransaction.tell(new WriteData(path, data, schemaContext).toSerializable(), null);
+ transactionContext(path).writeData(path, data);
}
@Override
createTransactionIfMissing(actorContext, path);
- final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
- remoteTransaction.tell(new MergeData(path, data, schemaContext).toSerializable(), null);
+ transactionContext(path).mergeData(path, data);
}
@Override
createTransactionIfMissing(actorContext, path);
- final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
- remoteTransaction.tell(new DeleteData(path).toSerializable(), null);
+ transactionContext(path).deleteData(path);
}
@Override
List<ActorPath> cohortPaths = new ArrayList<>();
for(TransactionContext transactionContext : remoteTransactionPaths.values()) {
- Object result = actorContext.executeRemoteOperation(transactionContext.getActor(),
- new ReadyTransaction().toSerializable(),
- ActorContext.ASK_DURATION
- );
+ Object result = transactionContext.readyTransaction();
if(result.getClass().equals(ReadyTransactionReply.SERIALIZABLE_CLASS)){
ReadyTransactionReply reply = ReadyTransactionReply.fromSerializable(actorContext.getActorSystem(),result);
@Override
public void close() {
for(TransactionContext transactionContext : remoteTransactionPaths.values()) {
- transactionContext.getActor().tell(
- new CloseTransaction().toSerializable(), null);
+ transactionContext.closeTransaction();
}
}
- private ActorSelection remoteTransactionFromIdentifier(YangInstanceIdentifier path){
+ private TransactionContext transactionContext(YangInstanceIdentifier path){
String shardName = shardNameFromIdentifier(path);
- return remoteTransactionPaths.get(shardName).getActor();
+ return remoteTransactionPaths.get(shardName);
}
private String shardNameFromIdentifier(YangInstanceIdentifier path){
return;
}
- Object response = actorContext.executeShardOperation(shardName, new CreateTransaction(identifier).toSerializable(), ActorContext.ASK_DURATION);
- if(response.getClass().equals(CreateTransactionReply.SERIALIZABLE_CLASS)){
- CreateTransactionReply reply = CreateTransactionReply.fromSerializable(response);
- String transactionPath = actorContext.getRemoteActorPath(shardName, reply.getTransactionPath());
+ try {
+ Object response = actorContext.executeShardOperation(shardName,
+ new CreateTransaction(identifier).toSerializable(),
+ ActorContext.ASK_DURATION);
+ if (response.getClass()
+ .equals(CreateTransactionReply.SERIALIZABLE_CLASS)) {
+ CreateTransactionReply reply =
+ CreateTransactionReply.fromSerializable(response);
+
+ String transactionPath = reply.getTransactionPath();
- ActorSelection transactionActor = actorContext.actorSelection(transactionPath);
- transactionContext = new TransactionContext(shardName, transactionPath, transactionActor);
+ LOG.info("Received transaction path = {}" , transactionPath );
- remoteTransactionPaths.put(shardName, transactionContext);
+ ActorSelection transactionActor =
+ actorContext.actorSelection(transactionPath);
+ transactionContext =
+ new TransactionContextImpl(shardName, transactionPath,
+ transactionActor);
+
+ remoteTransactionPaths.put(shardName, transactionContext);
+ }
+ } catch(TimeoutException e){
+ remoteTransactionPaths.put(shardName, new NoOpTransactionContext(shardName));
}
}
+ private interface TransactionContext {
+ String getShardName();
+
+ String getResolvedCohortPath(String cohortPath);
+
+ public void closeTransaction();
+
+ public Object readyTransaction();
- private class TransactionContext {
+ void deleteData(YangInstanceIdentifier path);
+
+ void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
+
+ ListenableFuture<Optional<NormalizedNode<?, ?>>> readData(final YangInstanceIdentifier path);
+
+ void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
+ }
+
+
+ private class TransactionContextImpl implements TransactionContext{
private final String shardName;
private final String actorPath;
private final ActorSelection actor;
- private TransactionContext(String shardName, String actorPath,
+ private TransactionContextImpl(String shardName, String actorPath,
ActorSelection actor) {
this.shardName = shardName;
this.actorPath = actorPath;
this.actor = actor;
}
-
- public String getShardName() {
+ @Override public String getShardName() {
return shardName;
}
- public String getActorPath() {
- return actorPath;
- }
-
- public ActorSelection getActor() {
+ private ActorSelection getActor() {
return actor;
}
- public String getResolvedCohortPath(String cohortPath){
+ @Override public String getResolvedCohortPath(String cohortPath){
return actorContext.resolvePath(actorPath, cohortPath);
}
+
+ @Override public void closeTransaction() {
+ getActor().tell(
+ new CloseTransaction().toSerializable(), null);
+ }
+
+ @Override public Object readyTransaction() {
+ return actorContext.executeRemoteOperation(getActor(),
+ new ReadyTransaction().toSerializable(),
+ ActorContext.ASK_DURATION
+ );
+
+ }
+
+ @Override public void deleteData(YangInstanceIdentifier path) {
+ getActor().tell(new DeleteData(path).toSerializable(), null);
+ }
+
+ @Override public void mergeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data){
+ getActor().tell(new MergeData(path, data, schemaContext).toSerializable(), null);
+ }
+
+ @Override public ListenableFuture<Optional<NormalizedNode<?, ?>>> readData(final YangInstanceIdentifier path) {
+
+ Callable<Optional<NormalizedNode<?,?>>> call = new Callable() {
+
+ @Override public Optional<NormalizedNode<?,?>> call() throws Exception {
+ Object response = actorContext
+ .executeRemoteOperation(getActor(), new ReadData(path).toSerializable(),
+ ActorContext.ASK_DURATION);
+ if(response.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)){
+ ReadDataReply reply = ReadDataReply.fromSerializable(schemaContext,path, response);
+ if(reply.getNormalizedNode() == null){
+ return Optional.absent();
+ }
+ //FIXME : A cast should not be required here ???
+ return (Optional<NormalizedNode<?, ?>>) Optional.of(reply.getNormalizedNode());
+ }
+
+ return Optional.absent();
+ }
+ };
+
+ ListenableFutureTask<Optional<NormalizedNode<?, ?>>>
+ future = ListenableFutureTask.create(call);
+
+ executor.submit(future);
+
+ return future;
+ }
+
+ @Override public void writeData(YangInstanceIdentifier path, NormalizedNode<?, ?> data) {
+ getActor().tell(new WriteData(path, data, schemaContext).toSerializable(), null);
+ }
+
+ }
+
+ private class NoOpTransactionContext implements TransactionContext {
+
+ private final Logger
+ LOG = LoggerFactory.getLogger(NoOpTransactionContext.class);
+
+ private final String shardName;
+
+ private ActorRef cohort;
+
+ public NoOpTransactionContext(String shardName){
+ this.shardName = shardName;
+ }
+ @Override public String getShardName() {
+ return shardName;
+
+ }
+
+ @Override public String getResolvedCohortPath(String cohortPath) {
+ return cohort.path().toString();
+ }
+
+ @Override public void closeTransaction() {
+ LOG.error("closeTransaction called");
+ }
+
+ @Override public Object readyTransaction() {
+ LOG.error("readyTransaction called");
+ cohort = actorContext.getActorSystem().actorOf(Props.create(NoOpCohort.class));
+ return new ReadyTransactionReply(cohort.path()).toSerializable();
+ }
+
+ @Override public void deleteData(YangInstanceIdentifier path) {
+ LOG.error("deleteData called path = {}", path);
+ }
+
+ @Override public void mergeData(YangInstanceIdentifier path,
+ NormalizedNode<?, ?> data) {
+ LOG.error("mergeData called path = {}", path);
+ }
+
+ @Override
+ public ListenableFuture<Optional<NormalizedNode<?, ?>>> readData(
+ YangInstanceIdentifier path) {
+ LOG.error("readData called path = {}", path);
+ return Futures.immediateFuture(
+ Optional.<NormalizedNode<?, ?>>absent());
+ }
+
+ @Override public void writeData(YangInstanceIdentifier path,
+ NormalizedNode<?, ?> data) {
+ LOG.error("writeData called path = {}", path);
+ }
}
+
+
}
package org.opendaylight.controller.cluster.datastore.exceptions;
public class PrimaryNotFoundException extends RuntimeException {
+ public PrimaryNotFoundException(String message){
+ super(message);
+ }
}
package org.opendaylight.controller.cluster.datastore.exceptions;
public class TimeoutException extends RuntimeException {
- public TimeoutException(Exception e){
- super(e);
+ public TimeoutException(String message, Exception e){
+ super(message, e);
}
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore.messages;
+
+public class PeerAddressResolved {
+ private final String peerId;
+ private final String peerAddress;
+
+ public PeerAddressResolved(String peerId, String peerAddress) {
+ this.peerId = peerId;
+ this.peerAddress = peerAddress;
+ }
+
+ public String getPeerId() {
+ return peerId;
+ }
+
+ public String getPeerAddress() {
+ return peerAddress;
+ }
+}
import akka.actor.ActorSystem;
import akka.actor.PoisonPill;
import akka.util.Timeout;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
import org.opendaylight.controller.cluster.datastore.Configuration;
import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
return found.getPrimaryPath();
}
- throw new PrimaryNotFoundException();
+ throw new PrimaryNotFoundException("Could not find primary for shardName " + shardName);
}
try {
return Await.result(future, AWAIT_DURATION);
} catch (Exception e) {
- throw new TimeoutException(e);
+ throw new TimeoutException("Sending message " + message.getClass().toString() + " to actor " + actor.toString() + " failed" , e);
}
}
try {
return Await.result(future, AWAIT_DURATION);
} catch (Exception e) {
- throw new TimeoutException(e);
+ throw new TimeoutException("Sending message " + message.getClass().toString() + " to actor " + actor.toString() + " failed" , e);
}
}
actorSystem.shutdown();
}
- public String getRemoteActorPath(final String shardName,
- final String localPathOfRemoteActor) {
- final String path = findPrimaryPath(shardName);
-
- LoadingCache<String, String> graphs = CacheBuilder.newBuilder()
- .expireAfterAccess(2, TimeUnit.SECONDS)
- .build(
- new CacheLoader<String, String>() {
- public String load(String key) {
- return resolvePath(path, localPathOfRemoteActor);
- }
- }
- );
- return graphs.getUnchecked(localPathOfRemoteActor);
- }
-
+ /**
+ * @deprecated Need to stop using this method. There are ways to send a
+ * remote ActorRef as a string which should be used instead of this hack
+ *
+ * @param primaryPath
+ * @param localPathOfRemoteActor
+ * @return
+ */
+ @Deprecated
public String resolvePath(final String primaryPath,
final String localPathOfRemoteActor) {
StringBuilder builder = new StringBuilder();
import akka.actor.ActorSystem;
import akka.testkit.JavaTestKit;
+import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
+import java.io.File;
+import java.io.IOException;
+
public abstract class AbstractActorTest {
private static ActorSystem system;
@BeforeClass
- public static void setUpClass() {
+ public static void setUpClass() throws IOException {
+ File journal = new File("journal");
+
+ if(journal.exists()) {
+ FileUtils.deleteDirectory(journal);
+ }
+
System.setProperty("shard.persistent", "false");
system = ActorSystem.create("test");
}
@AfterClass
- public static void tearDownClass() {
+ public static void tearDownClass() throws IOException {
JavaTestKit.shutdownActorSystem(system);
system = null;
+
+ File journal = new File("journal");
+
+ if(journal.exists()) {
+ FileUtils.deleteDirectory(journal);
+ }
}
protected ActorSystem getSystem() {
import scala.concurrent.Future;
import scala.concurrent.duration.FiniteDuration;
+import java.util.Collections;
+
public class BasicIntegrationTest extends AbstractActorTest {
@Test
new JavaTestKit(getSystem()) {{
- final Props props = Shard.props("config");
+ final Props props = Shard.props("config", Collections.EMPTY_MAP);
final ActorRef shard = getSystem().actorOf(props);
new Within(duration("5 seconds")) {
protected void run() {
+
shard.tell(
new UpdateSchemaContext(TestModel.createTestContext()),
getRef());
+
+ // Wait for Shard to become a Leader
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ // 1. Create a TransactionChain
shard.tell(new CreateTransactionChain().toSerializable(), getRef());
final ActorSelection transactionChain =
Assert.assertNotNull(transactionChain);
+ System.out.println("Successfully created transaction chain");
+
+ // 2. Create a Transaction on the TransactionChain
transactionChain.tell(new CreateTransaction("txn-1").toSerializable(), getRef());
final ActorSelection transaction =
Assert.assertNotNull(transaction);
- // Add a watch on the transaction actor so that we are notified when it dies
- final ActorRef transactionActorRef = watchActor(transaction);
+ System.out.println("Successfully created transaction");
+ // 3. Write some data
transaction.tell(new WriteData(TestModel.TEST_PATH,
ImmutableNodes.containerNode(TestModel.TEST_QNAME), TestModel.createTestContext()).toSerializable(),
getRef());
Assert.assertTrue(writeDone);
+ System.out.println("Successfully wrote data");
+
+ // 4. Ready the transaction for commit
+
transaction.tell(new ReadyTransaction().toSerializable(), getRef());
final ActorSelection cohort =
Assert.assertNotNull(cohort);
- // Add a watch on the transaction actor so that we are notified when it dies
- final ActorRef cohorActorRef = watchActor(cohort);
+ System.out.println("Successfully readied the transaction");
+
+ // 5. PreCommit the transaction
cohort.tell(new PreCommitTransaction().toSerializable(), getRef());
Assert.assertTrue(preCommitDone);
+ System.out.println("Successfully pre-committed the transaction");
+
+ // 6. Commit the transaction
cohort.tell(new CommitTransaction().toSerializable(), getRef());
// FIXME : Add assertions that the commit worked and that the cohort and transaction actors were terminated
+ System.out.println("TODO : Check Successfully committed the transaction");
}
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
-import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
import org.opendaylight.controller.md.cluster.datastore.model.PeopleModel;
import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
@Test
public void integrationTest() throws Exception {
- ShardStrategyFactory.setConfiguration(new MockConfiguration());
+ Configuration configuration = new ConfigurationImpl("module-shards.conf", "modules.conf");
+ ShardStrategyFactory.setConfiguration(configuration);
DistributedDataStore distributedDataStore =
- new DistributedDataStore(getSystem(), "config", new MockClusterWrapper(), new MockConfiguration());
+ new DistributedDataStore(getSystem(), "config", new MockClusterWrapper(), configuration);
distributedDataStore.onGlobalContextUpdated(TestModel.createTestContext());
+ Thread.sleep(1000);
+
DOMStoreReadWriteTransaction transaction =
distributedDataStore.newReadWriteTransaction();
distributedDataStore.onGlobalContextUpdated(SchemaContextHelper.full());
+ Thread.sleep(1000);
+
DOMStoreReadWriteTransaction transaction =
distributedDataStore.newReadWriteTransaction();
import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChain;
import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChainReply;
+import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@Test
public void testOnReceiveCreateTransactionChain() throws Exception {
new JavaTestKit(getSystem()) {{
- final Props props = Shard.props("config");
+ final Props props = Shard.props("config", Collections.EMPTY_MAP);
final ActorRef subject =
getSystem().actorOf(props, "testCreateTransactionChain");
+
+ // Wait for Shard to become a Leader
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
new Within(duration("1 seconds")) {
protected void run() {
@Test
public void testOnReceiveRegisterListener() throws Exception {
new JavaTestKit(getSystem()) {{
- final Props props = Shard.props("config");
+ final Props props = Shard.props("config", Collections.EMPTY_MAP);
final ActorRef subject =
getSystem().actorOf(props, "testRegisterChangeListener");
@Test
public void testCreateTransaction(){
new JavaTestKit(getSystem()) {{
- final Props props = Shard.props("config");
+ final Props props = Shard.props("config", Collections.EMPTY_MAP);
final ActorRef subject =
getSystem().actorOf(props, "testCreateTransaction");
+
+ // Wait for Shard to become a Leader
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+
new Within(duration("1 seconds")) {
protected void run() {
}
}.get(); // this extracts the received message
- assertEquals("Unexpected transaction path " + out,
- "akka://test/user/testCreateTransaction/shard-txn-1",
- out);
+ assertTrue("Unexpected transaction path " + out,
+ out.contains("akka://test/user/testCreateTransaction/shard-txn-1"));
expectNoMsg();
}
}};
}
+ @Test
+ public void testPeerAddressResolved(){
+ new JavaTestKit(getSystem()) {{
+ Map<String, String> peerAddresses = new HashMap<>();
+ peerAddresses.put("member-2", null);
+ final Props props = Shard.props("config", peerAddresses);
+ final ActorRef subject =
+ getSystem().actorOf(props, "testPeerAddressResolved");
+
+ new Within(duration("1 seconds")) {
+ protected void run() {
+ subject.tell(
+ new PeerAddressResolved("member-2", "akka://foobar"),
+ getRef());
+
+ expectNoMsg();
+ }
+
+
+ };
+ }};
+ }
private AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> noOpDataChangeListener() {
return new AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>() {
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import java.util.Collections;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@Test
public void testOnReceiveReadData() throws Exception {
new JavaTestKit(getSystem()) {{
- final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+ final ActorRef shard = getSystem().actorOf(Shard.props("config", Collections.EMPTY_MAP));
final Props props =
ShardTransaction.props(store.newReadWriteTransaction(), shard, testSchemaContext);
final ActorRef subject = getSystem().actorOf(props, "testReadData");
@Test
public void testOnReceiveReadDataWhenDataNotFound() throws Exception {
new JavaTestKit(getSystem()) {{
- final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+ final ActorRef shard = getSystem().actorOf(Shard.props("config", Collections.EMPTY_MAP));
final Props props =
ShardTransaction.props(store.newReadWriteTransaction(), shard, testSchemaContext);
final ActorRef subject = getSystem().actorOf(props, "testReadDataWhenDataNotFound");
@Test
public void testOnReceiveWriteData() throws Exception {
new JavaTestKit(getSystem()) {{
- final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+ final ActorRef shard = getSystem().actorOf(Shard.props("config", Collections.EMPTY_MAP));
final Props props =
ShardTransaction.props(store.newReadWriteTransaction(), shard, TestModel.createTestContext());
final ActorRef subject =
@Test
public void testOnReceiveMergeData() throws Exception {
new JavaTestKit(getSystem()) {{
- final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+ final ActorRef shard = getSystem().actorOf(Shard.props("config", Collections.EMPTY_MAP));
final Props props =
ShardTransaction.props(store.newReadWriteTransaction(), shard, testSchemaContext);
final ActorRef subject =
@Test
public void testOnReceiveDeleteData() throws Exception {
new JavaTestKit(getSystem()) {{
- final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+ final ActorRef shard = getSystem().actorOf(Shard.props("config", Collections.EMPTY_MAP));
final Props props =
ShardTransaction.props(store.newReadWriteTransaction(), shard, TestModel.createTestContext());
final ActorRef subject =
@Test
public void testOnReceiveReadyTransaction() throws Exception {
new JavaTestKit(getSystem()) {{
- final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+ final ActorRef shard = getSystem().actorOf(Shard.props("config", Collections.EMPTY_MAP));
final Props props =
ShardTransaction.props(store.newReadWriteTransaction(), shard, TestModel.createTestContext());
final ActorRef subject =
@Test
public void testOnReceiveCloseTransaction() throws Exception {
new JavaTestKit(getSystem()) {{
- final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+ final ActorRef shard = getSystem().actorOf(Shard.props("config", Collections.EMPTY_MAP));
final Props props =
ShardTransaction.props(store.newReadWriteTransaction(), shard, TestModel.createTestContext());
final ActorRef subject =
package org.opendaylight.controller.md.cluster.datastore.model;
+import java.math.BigInteger;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
MapEntryNode altima =
ImmutableNodes.mapEntryBuilder(CAR_QNAME, CAR_NAME_QNAME, "altima")
.withChild(ImmutableNodes.leafNode(CAR_NAME_QNAME, "altima"))
- .withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, 1000))
+ .withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, new BigInteger("1000")))
.build();
// Create an entry for the car accord
MapEntryNode honda =
ImmutableNodes.mapEntryBuilder(CAR_QNAME, CAR_NAME_QNAME, "accord")
.withChild(ImmutableNodes.leafNode(CAR_NAME_QNAME, "accord"))
- .withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, 2000))
+ .withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, new BigInteger("2000")))
.build();
cars.withChild(altima);
MapEntryNode jack =
ImmutableNodes.mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, "jack")
.withChild(ImmutableNodes.leafNode(PERSON_NAME_QNAME, "jack"))
- .withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 100))
+ .withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 100L))
.build();
// Create an entry for the person jill
MapEntryNode jill =
ImmutableNodes.mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, "jill")
.withChild(ImmutableNodes.leafNode(PERSON_NAME_QNAME, "jill"))
- .withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 200))
+ .withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 200L))
.build();
cars.withChild(jack);
public class SampleModelsTest {
@Test
public void testPeopleModel(){
- NormalizedNode<?, ?> expected = PeopleModel.create();
+ final NormalizedNode<?, ?> expected = PeopleModel.create();
- NormalizedNodeMessages.Container node =
+ final NormalizedNodeMessages.Container node =
new NormalizedNodeToNodeCodec(SchemaContextHelper.full())
.encode(YangInstanceIdentifier.of(PeopleModel.BASE_QNAME),
expected);
- NormalizedNodeMessages.Node normalizedNode =
+ final NormalizedNodeMessages.Node normalizedNode =
node.getNormalizedNode();
- NormalizedNode<?,?> actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(YangInstanceIdentifier.of(PeopleModel.BASE_QNAME),
+ final NormalizedNode<?,?> actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(YangInstanceIdentifier.of(PeopleModel.BASE_QNAME),
normalizedNode);
- Assert.assertEquals(expected.toString(), actual.toString());
+ Assert.assertEquals(expected, actual);
}
@Test
public void testCarsModel(){
- NormalizedNode<?, ?> expected = CarsModel.create();
+ final NormalizedNode<?, ?> expected = CarsModel.create();
- NormalizedNodeMessages.Container node =
+ final NormalizedNodeMessages.Container node =
new NormalizedNodeToNodeCodec(SchemaContextHelper.full())
.encode(YangInstanceIdentifier.of(CarsModel.BASE_QNAME),
expected);
- NormalizedNodeMessages.Node normalizedNode =
+ final NormalizedNodeMessages.Node normalizedNode =
node.getNormalizedNode();
- NormalizedNode<?,?> actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(
+ final NormalizedNode<?,?> actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(
YangInstanceIdentifier.of(CarsModel.BASE_QNAME),
normalizedNode);
- Assert.assertEquals(expected.toString(), actual.toString());
+ Assert.assertEquals(expected, actual);
}
}
{
name="people-1"
replicas = [
- "member-1",
- "member-2",
- "member-3"
+ "member-1"
]
}
]
{
name="cars-1"
replicas = [
- "member-4",
- "member-1",
- "member-5"
+ "member-1"
+ ]
+ }
+ ]
+ },
+ {
+ name = "test"
+ shards = [
+ {
+ name="test-1"
+ replicas = [
+ "member-1"
]
}
]
name = "cars"
namespace = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:cars"
shard-strategy = "module"
+ },
+ {
+ name = "test"
+ namespace = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test"
+ shard-strategy = "module"
}
]
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
public interface SchemaService extends BrokerService {
*/
SchemaContext getGlobalContext();
- ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(SchemaServiceListener listener);
+ /**
+ * Register a listener for changes in schema context.
+ *
+ * @param listener Listener which should be registered
+ * @return Listener registration handle
+ */
+ ListenerRegistration<SchemaContextListener> registerSchemaContextListener(SchemaContextListener listener);
}
wrappedStore.changeDelegate(legacyStore);
wrappedStore.setValidationEnabled(false);
- schemaService.registerSchemaServiceListener(wrappedStore);
+ schemaService.registerSchemaContextListener(wrappedStore);
dataService.registerConfigurationReader(rootPath, wrappedStore);
dataService.registerCommitHandler(rootPath, wrappedStore);
//we will default to InMemoryDOMDataStore creation
operStore = new InMemoryDOMDataStore("DOM-OPER", storeExecutor);
//here we will register the SchemaContext listener
- getSchemaServiceDependency().registerSchemaServiceListener((InMemoryDOMDataStore)operStore);
+ getSchemaServiceDependency().registerSchemaContextListener((InMemoryDOMDataStore)operStore);
}
DOMStore configStore = getConfigDataStoreDependency();
//we will default to InMemoryDOMDataStore creation
configStore = new InMemoryDOMDataStore("DOM-CFG", storeExecutor);
//here we will register the SchemaContext listener
- getSchemaServiceDependency().registerSchemaServiceListener((InMemoryDOMDataStore)configStore);
+ getSchemaServiceDependency().registerSchemaContextListener((InMemoryDOMDataStore)configStore);
}
ImmutableMap<LogicalDatastoreType, DOMStore> datastores = ImmutableMap
.<LogicalDatastoreType, DOMStore> builder().put(LogicalDatastoreType.OPERATIONAL, operStore)
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
@Override
- public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener arg0) {
- return delegate.registerSchemaServiceListener(arg0);
+ public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener arg0) {
+ return delegate.registerSchemaContextListener(arg0);
}
@Override
+/*
+ * 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.md.sal.dom.broker.impl.compat;
import javax.annotation.concurrent.ThreadSafe;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
@ThreadSafe
public class BackwardsCompatibleDataBroker implements DataProviderService {
private final DOMDataBroker backingBroker;
private volatile DataNormalizer normalizer;
- private final ListenerRegistration<SchemaServiceListener> schemaReg;
+ private final ListenerRegistration<SchemaContextListener> schemaReg;
public BackwardsCompatibleDataBroker(final DOMDataBroker newBiDataImpl, final SchemaService schemaService) {
backingBroker = newBiDataImpl;
- schemaReg = schemaService.registerSchemaServiceListener(new SchemaListener());
+ schemaReg = schemaService.registerSchemaContextListener(new SchemaListener());
}
@Override
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
public class BackwardsCompatibleMountPoint implements MountProvisionInstance, SchemaContextProvider, SchemaService {
private final NotificationPublishService notificationPublishService;
private final RpcProvisionRegistry rpcs;
- private final ListenerRegistry<SchemaServiceListener> schemaListenerRegistry = new ListenerRegistry<>();
+ private final ListenerRegistry<SchemaContextListener> schemaListenerRegistry = new ListenerRegistry<>();
private SchemaContext schemaContext;
}
@Override
- public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
+ public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
return schemaListenerRegistry.register(listener);
}
@Override
public void setSchemaContext(final SchemaContext schemaContext) {
this.schemaContext = schemaContext;
- for (ListenerRegistration<SchemaServiceListener> schemaServiceListenerListenerRegistration : schemaListenerRegistry.getListeners()) {
+ for (ListenerRegistration<SchemaContextListener> schemaServiceListenerListenerRegistration : schemaListenerRegistry.getListeners()) {
schemaServiceListenerListenerRegistration.getInstance().onGlobalContextUpdated(schemaContext);
}
}
import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.opendaylight.yangtools.yang.parser.impl.util.URLSchemaContextResolver;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
-public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaServiceListener, SchemaServiceListener>, AutoCloseable {
+public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(GlobalBundleScanningSchemaServiceImpl.class);
- private final ListenerRegistry<SchemaServiceListener> listeners = new ListenerRegistry<>();
+ private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
private final URLSchemaContextResolver contextResolver = new URLSchemaContextResolver();
private final BundleScanner scanner = new BundleScanner();
private final BundleContext context;
- private ServiceTracker<SchemaServiceListener, SchemaServiceListener> listenerTracker;
+ private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
private BundleTracker<Iterable<Registration>> bundleTracker;
private boolean starting = true;
private static GlobalBundleScanningSchemaServiceImpl instance;
public void start() {
checkState(context != null);
- listenerTracker = new ServiceTracker<>(context, SchemaServiceListener.class, GlobalBundleScanningSchemaServiceImpl.this);
+ listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, GlobalBundleScanningSchemaServiceImpl.this);
bundleTracker = new BundleTracker<>(context, BundleEvent.RESOLVED | BundleEvent.UNRESOLVED, scanner);
bundleTracker.open();
listenerTracker.open();
}
@Override
- public synchronized ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
+ public synchronized ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
if(potentialCtx.isPresent()) {
listener.onGlobalContextUpdated(potentialCtx.get());
private synchronized void updateContext(final SchemaContext snapshot) {
Object[] services = listenerTracker.getServices();
- for (ListenerRegistration<SchemaServiceListener> listener : listeners) {
+ for (ListenerRegistration<SchemaContextListener> listener : listeners) {
try {
listener.getInstance().onGlobalContextUpdated(snapshot);
} catch (Exception e) {
}
if (services != null) {
for (Object rawListener : services) {
- SchemaServiceListener listener = (SchemaServiceListener) rawListener;
+ final SchemaContextListener listener = (SchemaContextListener) rawListener;
try {
listener.onGlobalContextUpdated(snapshot);
} catch (Exception e) {
}
@Override
- public synchronized SchemaServiceListener addingService(final ServiceReference<SchemaServiceListener> reference) {
+ public synchronized SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
- SchemaServiceListener listener = context.getService(reference);
+ SchemaContextListener listener = context.getService(reference);
SchemaContext _ctxContext = getGlobalContext();
if (getContext() != null && _ctxContext != null) {
listener.onGlobalContextUpdated(_ctxContext);
}
@Override
- public void modifiedService(final ServiceReference<SchemaServiceListener> reference, final SchemaServiceListener service) {
+ public void modifiedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
// NOOP
}
@Override
- public void removedService(final ServiceReference<SchemaServiceListener> reference, final SchemaServiceListener service) {
+ public void removedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
context.ungetService(reference);
}
}
package org.opendaylight.controller.sal.dom.broker.osgi;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.osgi.framework.ServiceReference;
public class SchemaServiceProxy extends AbstractBrokerServiceProxy<SchemaService> implements SchemaService {
}
@Override
- public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(SchemaServiceListener listener) {
- ListenerRegistration<SchemaServiceListener> registration = getDelegate().registerSchemaServiceListener(listener);
+ public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(SchemaContextListener listener) {
+ ListenerRegistration<SchemaContextListener> registration = getDelegate().registerSchemaContextListener(listener);
addRegistration(registration);
return registration;
}
-
-
-
}
@Override
public java.lang.AutoCloseable createInstance() {
XSQLAdapter xsqlAdapter = XSQLAdapter.getInstance();
- getSchemaServiceDependency().registerSchemaServiceListener(xsqlAdapter);
+ getSchemaServiceDependency().registerSchemaContextListener(xsqlAdapter);
xsqlAdapter.setDataBroker(getAsyncDataBrokerDependency());
XSQLProvider p = new XSQLProvider();
p.buildXSQL(getDataBrokerDependency());
@Override
public java.lang.AutoCloseable createInstance() {
InMemoryDOMDataStore ids = new InMemoryDOMDataStore("DOM-CFG", MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
- getSchemaServiceDependency().registerSchemaServiceListener(ids);
+ getSchemaServiceDependency().registerSchemaContextListener(ids);
return ids;
}
@Override
public java.lang.AutoCloseable createInstance() {
InMemoryDOMDataStore ids = new InMemoryDOMDataStore("DOM-OPER", MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
- getOperationalSchemaServiceDependency().registerSchemaServiceListener(ids);
+ getOperationalSchemaServiceDependency().registerSchemaContextListener(ids);
return ids;
}
import java.io.File;
import java.io.InputStream;
import java.net.InetSocketAddress;
+import java.util.List;
import java.util.concurrent.ExecutorService;
+import org.opendaylight.controller.config.api.JmxAttributeValidationException;
import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
+import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceSalFacade;
import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
import org.opendaylight.controller.sal.core.api.Broker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.base.Optional;
+
/**
*
*/
private static AbstractCachingSchemaSourceProvider<String, InputStream> GLOBAL_NETCONF_SOURCE_PROVIDER = null;
private BundleContext bundleContext;
+ private Optional<NetconfSessionCapabilities> userCapabilities;
public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
checkNotNull(getPassword(), passwordJmxAttribute);
}
+ userCapabilities = getUserCapabilities();
+
}
- private boolean isHostAddressPresent(Host address) {
+ private boolean isHostAddressPresent(final Host address) {
return address.getDomainName() != null ||
address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
}
final Broker domBroker = getDomRegistryDependency();
final BindingAwareBroker bindingBroker = getBindingRegistryDependency();
- final RemoteDeviceHandler salFacade = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext, globalProcessingExecutor);
+ final RemoteDeviceHandler<NetconfSessionCapabilities> salFacade
+ = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext, globalProcessingExecutor);
final NetconfDevice device =
NetconfDevice.createNetconfDevice(id, getGlobalNetconfSchemaProvider(), globalProcessingExecutor, salFacade);
- final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(id, device);
+
+ final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
+ new NetconfDeviceCommunicator(id, device, userCapabilities.get()) : new NetconfDeviceCommunicator(id, device);
+
final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
final NetconfClientDispatcher dispatcher = getClientDispatcherDependency();
};
}
+ private Optional<NetconfSessionCapabilities> getUserCapabilities() {
+ if(getYangModuleCapabilities() == null) {
+ return Optional.absent();
+ }
+
+ final List<String> capabilities = getYangModuleCapabilities().getCapability();
+ if(capabilities == null || capabilities.isEmpty()) {
+ return Optional.absent();
+ }
+
+ final NetconfSessionCapabilities parsedOverrideCapabilities = NetconfSessionCapabilities.fromStrings(capabilities);
+ JmxAttributeValidationException.checkCondition(
+ parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
+ "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
+ " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
+ yangModuleCapabilitiesJmxAttribute);
+
+ return Optional.of(parsedOverrideCapabilities);
+ }
+
private synchronized AbstractCachingSchemaSourceProvider<String, InputStream> getGlobalNetconfSchemaProvider() {
if(GLOBAL_NETCONF_SOURCE_PROVIDER == null) {
final String storageFile = "cache/schema";
if(getAddress().getDomainName() != null) {
return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
} else {
- IpAddress ipAddress = getAddress().getIpAddress();
- String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
+ final IpAddress ipAddress = getAddress().getIpAddress();
+ final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
return new InetSocketAddress(ip, getPort().getValue());
}
}
// Unable to initialize device, set as disconnected
logger.error("{}: Initialization failed", id, t);
salFacade.onDeviceDisconnected();
+ // TODO ssh connection is still open if sal initialization fails
}
});
}
*/
package org.opendaylight.controller.sal.connect.netconf.listener;
+import com.google.common.base.Optional;
+import com.google.common.base.Strings;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.FutureListener;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
-
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Strings;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.FutureListener;
-
public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
+ private final Optional<NetconfSessionCapabilities> overrideNetconfCapabilities;
private final RemoteDeviceId id;
private final Lock sessionLock = new ReentrantLock();
+ private final Queue<Request> requests = new ArrayDeque<>();
+ private NetconfClientSession session;
+
+ public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice,
+ final NetconfSessionCapabilities netconfSessionCapabilities) {
+ this(id, remoteDevice, Optional.of(netconfSessionCapabilities));
+ }
+
public NetconfDeviceCommunicator(final RemoteDeviceId id,
- final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
+ final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
+ this(id, remoteDevice, Optional.<NetconfSessionCapabilities>absent());
+ }
+
+ private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice,
+ final Optional<NetconfSessionCapabilities> overrideNetconfCapabilities) {
this.id = id;
this.remoteDevice = remoteDevice;
+ this.overrideNetconfCapabilities = overrideNetconfCapabilities;
}
- private final Queue<Request> requests = new ArrayDeque<>();
- private NetconfClientSession session;
-
@Override
public void onSessionUp(final NetconfClientSession session) {
sessionLock.lock();
logger.debug("{}: Session established", id);
this.session = session;
- final NetconfSessionCapabilities netconfSessionCapabilities =
+ NetconfSessionCapabilities netconfSessionCapabilities =
NetconfSessionCapabilities.fromNetconfSession(session);
logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
+ if(overrideNetconfCapabilities.isPresent()) {
+ netconfSessionCapabilities = netconfSessionCapabilities.replaceModuleCaps(overrideNetconfCapabilities.get());
+ logger.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id, netconfSessionCapabilities);
+ }
+
remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
}
finally {
return;
}
- request.future.set( RpcResultBuilder.<NetconfMessage>success( message ).build() );
+ request.future.set( RpcResultBuilder.success( message ).build() );
}
}
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
+import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.LoggerFactory;
public final class NetconfSessionCapabilities {
+
private static final class ParameterMatcher {
private final Predicate<String> predicate;
private final int skipLength;
};
private final Set<QName> moduleBasedCaps;
- private final Set<String> capabilities;
+ private final Set<String> nonModuleCaps;
- private NetconfSessionCapabilities(final Set<String> capabilities, final Set<QName> moduleBasedCaps) {
- this.capabilities = Preconditions.checkNotNull(capabilities);
+ private NetconfSessionCapabilities(final Set<String> nonModuleCaps, final Set<QName> moduleBasedCaps) {
+ this.nonModuleCaps = Preconditions.checkNotNull(nonModuleCaps);
this.moduleBasedCaps = Preconditions.checkNotNull(moduleBasedCaps);
}
return moduleBasedCaps;
}
- public boolean containsCapability(final String capability) {
- return capabilities.contains(capability);
+ public Set<String> getNonModuleCaps() {
+ return nonModuleCaps;
+ }
+
+ public boolean containsNonModuleCapability(final String capability) {
+ return nonModuleCaps.contains(capability);
}
- public boolean containsCapability(final QName capability) {
+ public boolean containsModuleCapability(final QName capability) {
return moduleBasedCaps.contains(capability);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
- .add("capabilities", capabilities)
+ .add("capabilities", nonModuleCaps)
+ .add("moduleBasedCapabilities", moduleBasedCaps)
.add("rollback", isRollbackSupported())
.add("monitoring", isMonitoringSupported())
.toString();
}
public boolean isRollbackSupported() {
- return containsCapability(NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString());
+ return containsNonModuleCapability(NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString());
+ }
+
+ public boolean isCandidateSupported() {
+ return containsNonModuleCapability(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
}
public boolean isMonitoringSupported() {
- return containsCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)
- || containsCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
+ return containsModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)
+ || containsNonModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
+ }
+
+ public NetconfSessionCapabilities replaceModuleCaps(final NetconfSessionCapabilities netconfSessionModuleCapabilities) {
+ final Set<QName> moduleBasedCaps = Sets.newHashSet(netconfSessionModuleCapabilities.getModuleBasedCaps());
+
+ // Preserve monitoring module, since it indicates support for ietf-netconf-monitoring
+ if(containsModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)) {
+ moduleBasedCaps.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING);
+ }
+ return new NetconfSessionCapabilities(getNonModuleCaps(), moduleBasedCaps);
}
public static NetconfSessionCapabilities fromNetconfSession(final NetconfClientSession session) {
public static NetconfSessionCapabilities fromStrings(final Collection<String> capabilities) {
final Set<QName> moduleBasedCaps = new HashSet<>();
+ final Set<String> nonModuleCaps = Sets.newHashSet(capabilities);
for (final String capability : capabilities) {
final int qmark = capability.indexOf('?');
String revision = REVISION_PARAM.from(queryParams);
if (revision != null) {
moduleBasedCaps.add(QName.create(namespace, revision, moduleName));
+ nonModuleCaps.remove(capability);
continue;
}
// FIXME: do we really want to continue here?
moduleBasedCaps.add(QName.create(namespace, revision, moduleName));
+ nonModuleCaps.remove(capability);
}
- return new NetconfSessionCapabilities(ImmutableSet.copyOf(capabilities), ImmutableSet.copyOf(moduleBasedCaps));
+ return new NetconfSessionCapabilities(ImmutableSet.copyOf(nonModuleCaps), ImmutableSet.copyOf(moduleBasedCaps));
}
}
@Override
public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
- return new NetconfDeviceReadOnlyTx(rpc, normalizer);
+ return new NetconfDeviceReadOnlyTx(rpc, normalizer, id);
}
@Override
@Override
public DOMDataWriteTransaction newWriteOnlyTransaction() {
- // FIXME detect if candidate is supported, true is hardcoded
- return new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, true, netconfSessionPreferences.isRollbackSupported());
+ return new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, netconfSessionPreferences.isCandidateSupported(), netconfSessionPreferences.isRollbackSupported());
}
@Override
import com.google.common.base.Function;
import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
+import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
import org.opendaylight.controller.sal.core.api.RpcImplementation;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
public final class NetconfDeviceReadOnlyTx implements DOMDataReadOnlyTransaction {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceReadOnlyTx.class);
private final RpcImplementation rpc;
private final DataNormalizer normalizer;
+ private final RemoteDeviceId id;
- public NetconfDeviceReadOnlyTx(final RpcImplementation rpc, final DataNormalizer normalizer) {
+ public NetconfDeviceReadOnlyTx(final RpcImplementation rpc, final DataNormalizer normalizer, final RemoteDeviceId id) {
this.rpc = rpc;
this.normalizer = normalizer;
+ this.id = id;
}
public ListenableFuture<Optional<NormalizedNode<?, ?>>> readConfigurationData(final YangInstanceIdentifier path) {
return Futures.transform(future, new Function<RpcResult<CompositeNode>, Optional<NormalizedNode<?, ?>>>() {
@Override
public Optional<NormalizedNode<?, ?>> apply(final RpcResult<CompositeNode> result) {
+ checkReadSuccess(result, path);
+
final CompositeNode data = result.getResult().getFirstCompositeByName(NETCONF_DATA_QNAME);
final CompositeNode node = (CompositeNode) findNode(data, path);
});
}
+ private void checkReadSuccess(final RpcResult<CompositeNode> result, final YangInstanceIdentifier path) {
+ LOG.warn("{}: Unable to read data: {}, errors: {}", id, path, result.getErrors());
+ Preconditions.checkArgument(result.isSuccessful(), "%s: Unable to read data: %s, errors: %s", id, path, result.getErrors());
+ }
+
private Optional<NormalizedNode<?, ?>> transform(final YangInstanceIdentifier path, final CompositeNode node) {
if(node == null) {
return Optional.absent();
try {
return Optional.<NormalizedNode<?, ?>>of(normalizer.toNormalized(path, node).getValue());
} catch (final Exception e) {
- LOG.error("Unable to normalize data for {}, data: {}", path, node, e);
+ LOG.error("{}: Unable to normalize data for {}, data: {}", id, path, node, e);
throw e;
}
}
return Futures.transform(future, new Function<RpcResult<CompositeNode>, Optional<NormalizedNode<?, ?>>>() {
@Override
public Optional<NormalizedNode<?, ?>> apply(final RpcResult<CompositeNode> result) {
+ checkReadSuccess(result, path);
+
final CompositeNode data = result.getResult().getFirstCompositeByName(NETCONF_DATA_QNAME);
final CompositeNode node = (CompositeNode) findNode(data, path);
@Override
public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- final YangInstanceIdentifier legacyPath = toLegacyPath(normalizer, path);
+ final YangInstanceIdentifier legacyPath = toLegacyPath(normalizer, path, id);
switch (store) {
case CONFIGURATION : {
}
}
- throw new IllegalArgumentException(String.format("Cannot read data %s for %s datastore, unknown datastore type", path, store));
+ throw new IllegalArgumentException(String.format("%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
}
- static YangInstanceIdentifier toLegacyPath(final DataNormalizer normalizer, final YangInstanceIdentifier path) {
+ static YangInstanceIdentifier toLegacyPath(final DataNormalizer normalizer, final YangInstanceIdentifier path, final RemoteDeviceId id) {
try {
return normalizer.toLegacy(path);
} catch (final DataNormalizationException e) {
- throw new IllegalArgumentException("Cannot normalize path " + path, e);
+ throw new IllegalArgumentException(id + ": Cannot normalize path " + path, e);
}
}
package org.opendaylight.controller.sal.connect.netconf.sal.tx;
+import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.DISCARD_CHANGES_RPC_CONTENT;
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME;
-import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME;
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME;
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DEFAULT_OPERATION_QNAME;
+import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME;
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME;
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_ERROR_OPTION_QNAME;
import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_OPERATION_QNAME;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
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 java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
-import javax.annotation.Nullable;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NetconfDeviceWriteOnlyTx implements DOMDataWriteTransaction {
+public class NetconfDeviceWriteOnlyTx implements DOMDataWriteTransaction, FutureCallback<RpcResult<TransactionStatus>> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceWriteOnlyTx.class);
private final RemoteDeviceId id;
private final RpcImplementation rpc;
private final DataNormalizer normalizer;
+
private final boolean rollbackSupported;
+ private final boolean candidateSupported;
private final CompositeNode targetNode;
+ // Allow commit to be called only once
+ private final AtomicBoolean finished = new AtomicBoolean(false);
+
public NetconfDeviceWriteOnlyTx(final RemoteDeviceId id, final RpcImplementation rpc, final DataNormalizer normalizer, final boolean candidateSupported, final boolean rollbackOnErrorSupported) {
this.id = id;
this.rpc = rpc;
this.normalizer = normalizer;
- this.targetNode = getTargetNode(candidateSupported);
+
+ this.candidateSupported = candidateSupported;
+ this.targetNode = getTargetNode(this.candidateSupported);
this.rollbackSupported = rollbackOnErrorSupported;
}
- // FIXME add logging
-
@Override
public boolean cancel() {
- if(isCommitted()) {
+ if(isFinished()) {
return false;
}
return discardChanges();
}
- private boolean isCommitted() {
- // TODO 732
- return true;
+ private boolean isFinished() {
+ return finished.get();
}
private boolean discardChanges() {
- // TODO 732
+ finished.set(true);
+
+ if(candidateSupported) {
+ sendDiscardChanges();
+ }
return true;
}
// TODO should the edit operations be blocking ?
+ // TODO should the discard-changes operations be blocking ?
@Override
public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ checkNotFinished();
Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can merge only configuration, not %s", store);
try {
- final YangInstanceIdentifier legacyPath = NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path);
+ final YangInstanceIdentifier legacyPath = NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path, id);
final CompositeNode legacyData = normalizer.toLegacy(path, data);
- sendEditRpc(createEditConfigStructure(legacyPath, Optional.of(ModifyAction.REPLACE), Optional.fromNullable(legacyData)), Optional.of(ModifyAction.NONE));
+ sendEditRpc(
+ createEditConfigStructure(legacyPath, Optional.of(ModifyAction.REPLACE), Optional.fromNullable(legacyData)), Optional.of(ModifyAction.NONE));
} catch (final ExecutionException e) {
- LOG.warn("Error putting data to {}, data: {}, discarding changes", path, data, e);
+ LOG.warn("{}: Error putting data to {}, data: {}, discarding changes", id, path, data, e);
discardChanges();
- throw new RuntimeException("Error while replacing " + path, e);
+ throw new RuntimeException(id + ": Error while replacing " + path, e);
}
}
+ private void checkNotFinished() {
+ Preconditions.checkState(isFinished() == false, "%s: Transaction %s already finished", id, getIdentifier());
+ }
+
@Override
public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
- Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can merge only configuration, not %s", store);
+ checkNotFinished();
+ Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "%s: Can merge only configuration, not %s", id, store);
try {
- final YangInstanceIdentifier legacyPath = NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path);
+ final YangInstanceIdentifier legacyPath = NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path, id);
final CompositeNode legacyData = normalizer.toLegacy(path, data);
sendEditRpc(
createEditConfigStructure(legacyPath, Optional.<ModifyAction> absent(), Optional.fromNullable(legacyData)), Optional.<ModifyAction> absent());
} catch (final ExecutionException e) {
- LOG.warn("Error merging data to {}, data: {}, discarding changes", path, data, e);
+ LOG.warn("{}: Error merging data to {}, data: {}, discarding changes", id, path, data, e);
discardChanges();
- throw new RuntimeException("Error while merging " + path, e);
+ throw new RuntimeException(id + ": Error while merging " + path, e);
}
}
@Override
public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can merge only configuration, not %s", store);
+ checkNotFinished();
+ Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "%s: Can merge only configuration, not %s", id, store);
try {
- sendEditRpc(createEditConfigStructure(NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path), Optional.of(ModifyAction.DELETE), Optional.<CompositeNode>absent()), Optional.of(ModifyAction.NONE));
+ sendEditRpc(
+ createEditConfigStructure(NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path, id), Optional.of(ModifyAction.DELETE), Optional.<CompositeNode>absent()), Optional.of(ModifyAction.NONE));
} catch (final ExecutionException e) {
- LOG.warn("Error deleting data {}, discarding changes", path, e);
+ LOG.warn("{}: Error deleting data {}, discarding changes", id, path, e);
discardChanges();
- throw new RuntimeException("Error while deleting " + path, e);
+ throw new RuntimeException(id + ": Error while deleting " + path, e);
}
}
@Override
public CheckedFuture<Void, TransactionCommitFailedException> submit() {
final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
- @Nullable
@Override
- public Void apply(@Nullable final RpcResult<TransactionStatus> input) {
+ public Void apply(final RpcResult<TransactionStatus> input) {
return null;
}
});
@Override
public ListenableFuture<RpcResult<TransactionStatus>> commit() {
- // FIXME do not allow commit if closed or failed
+ checkNotFinished();
+ finished.set(true);
- final ListenableFuture<RpcResult<CompositeNode>> rpcResult = rpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, getCommitRequest());
- return Futures.transform(rpcResult, new Function<RpcResult<CompositeNode>, RpcResult<TransactionStatus>>() {
- @Override
- public RpcResult<TransactionStatus> apply(@Nullable final RpcResult<CompositeNode> input) {
- if(input.isSuccessful()) {
- return RpcResultBuilder.success(TransactionStatus.COMMITED).build();
- } else {
- final RpcResultBuilder<TransactionStatus> failed = RpcResultBuilder.failed();
- for (final RpcError rpcError : input.getErrors()) {
- failed.withError(rpcError.getErrorType(), rpcError.getTag(), rpcError.getMessage(), rpcError.getApplicationTag(), rpcError.getInfo(), rpcError.getCause());
+ if(candidateSupported == false) {
+ return Futures.immediateFuture(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
+ }
+
+ final ListenableFuture<RpcResult<CompositeNode>> rpcResult = rpc.invokeRpc(
+ NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+
+ final ListenableFuture<RpcResult<TransactionStatus>> transformed = Futures.transform(rpcResult,
+ new Function<RpcResult<CompositeNode>, RpcResult<TransactionStatus>>() {
+ @Override
+ public RpcResult<TransactionStatus> apply(final RpcResult<CompositeNode> input) {
+ if (input.isSuccessful()) {
+ return RpcResultBuilder.success(TransactionStatus.COMMITED).build();
+ } else {
+ final RpcResultBuilder<TransactionStatus> failed = RpcResultBuilder.failed();
+ for (final RpcError rpcError : input.getErrors()) {
+ failed.withError(rpcError.getErrorType(), rpcError.getTag(), rpcError.getMessage(),
+ rpcError.getApplicationTag(), rpcError.getInfo(), rpcError.getCause());
+ }
+ return failed.build();
+ }
}
- return failed.build();
- }
- }
- });
+ });
- // FIXME 732 detect commit failure
+ Futures.addCallback(transformed, this);
+ return transformed;
+ }
+
+ @Override
+ public void onSuccess(final RpcResult<TransactionStatus> result) {
+ LOG.debug("{}: Write successful, transaction: {}", id, getIdentifier());
+ }
+
+ @Override
+ public void onFailure(final Throwable t) {
+ LOG.warn("{}: Write failed, transaction {}, discarding changes", id, getIdentifier(), t);
+ discardChanges();
}
private void sendEditRpc(final CompositeNode editStructure, final Optional<ModifyAction> defaultOperation) throws ExecutionException {
}
}
+ private void sendDiscardChanges() {
+ final ListenableFuture<RpcResult<CompositeNode>> discardFuture = rpc.invokeRpc(NETCONF_DISCARD_CHANGES_QNAME, DISCARD_CHANGES_RPC_CONTENT);
+ Futures.addCallback(discardFuture, new FutureCallback<RpcResult<CompositeNode>>() {
+ @Override
+ public void onSuccess(final RpcResult<CompositeNode> result) {
+ LOG.debug("{}: Discarding transaction: {}", id, getIdentifier());
+ }
+
+ @Override
+ public void onFailure(final Throwable t) {
+ LOG.error("{}: Discarding changes failed, transaction: {}. Device configuration might be corrupted", id, getIdentifier(), t);
+ throw new RuntimeException(id + ": Discarding changes failed, transaction " + getIdentifier(), t);
+ }
+ });
+ }
+
private CompositeNode createEditConfigStructure(final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
final Optional<CompositeNode> lastChildOverride) {
Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath);
}
}
- private ImmutableCompositeNode getCommitRequest() {
- final CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
- commitInput.setQName(NETCONF_COMMIT_QNAME);
- return commitInput.toInstance();
- }
-
-
@Override
public Object getIdentifier() {
return this;
import org.opendaylight.yangtools.yang.data.api.Node;
import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
public class NetconfMessageTransformUtil {
- private NetconfMessageTransformUtil() {
- }
+ private NetconfMessageTransformUtil() {}
public static final QName IETF_NETCONF_MONITORING = QName.create("urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring", "2010-10-04", "ietf-netconf-monitoring");
public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
+ public static QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
+
public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
.create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
+ public static URI NETCONF_CANDIDATE_URI = URI
+ .create("urn:ietf:params:netconf:capability:candidate:1.0");
+
+ // Discard changes message
+ public static final CompositeNode DISCARD_CHANGES_RPC_CONTENT =
+ NodeFactory.createImmutableCompositeNode(NETCONF_DISCARD_CHANGES_QNAME, null, Collections.<Node<?>>emptyList());
+
+ // Commit changes message
+ public static final CompositeNode COMMIT_RPC_CONTENT =
+ NodeFactory.createImmutableCompositeNode(NETCONF_COMMIT_QNAME, null, Collections.<Node<?>>emptyList());
+
public static Node<?> toFilterStructure(final YangInstanceIdentifier identifier) {
Node<?> previous = null;
if (Iterables.isEmpty(identifier.getPathArguments())) {
return it.toInstance();
}
}
-
}
type string;
}
+ container yang-module-capabilities {
+ leaf-list capability {
+ type string;
+ description "Set a list of capabilities to override capabilities provided in device's hello message.
+ Can be used for devices that do not report any yang modules in their hello message";
+ }
+ }
+
container dom-registry {
uses config:service-ref {
refine type {
package org.opendaylight.controller.sal.connect.netconf.listener;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.same;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.RPC_REPLY_KEY;
+import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.ListenableFuture;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
-
import java.io.ByteArrayInputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
-
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Matchers.same;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.RPC_REPLY_KEY;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
-
import org.apache.commons.lang3.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import com.google.common.base.Strings;
-import com.google.common.collect.Sets;
-import com.google.common.util.concurrent.ListenableFuture;
-
public class NetconfDeviceCommunicatorTest {
@Mock
verify( mockDevice ).onRemoteSessionUp( netconfSessionCapabilities.capture(), eq( communicator ) );
NetconfSessionCapabilities actualCapabilites = netconfSessionCapabilities.getValue();
- assertEquals( "containsCapability", true, actualCapabilites.containsCapability(
- NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString() ) );
- assertEquals( "containsCapability", true, actualCapabilites.containsCapability( testCapability ) );
+ assertEquals( "containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
+ NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()) );
+ assertEquals( "containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability) );
assertEquals( "getModuleBasedCaps", Sets.newHashSet(
QName.create( "urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module" )),
actualCapabilites.getModuleBasedCaps() );
--- /dev/null
+package org.opendaylight.controller.sal.connect.netconf.listener;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+import com.google.common.collect.Lists;
+import java.util.List;
+import org.junit.Test;
+import org.junit.matchers.JUnitMatchers;
+import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
+import org.opendaylight.yangtools.yang.common.QName;
+
+public class NetconfSessionCapabilitiesTest {
+
+ @Test
+ public void testMerge() throws Exception {
+ final List<String> caps1 = Lists.newArrayList(
+ "namespace:1?module=module1&revision=2012-12-12",
+ "namespace:2?module=module2&revision=2012-12-12",
+ "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:netconf:base:1.0",
+ "urn:ietf:params:netconf:capability:rollback-on-error:1.0"
+ );
+ final NetconfSessionCapabilities sessionCaps1 = NetconfSessionCapabilities.fromStrings(caps1);
+ assertCaps(sessionCaps1, 2, 3);
+
+ final List<String> caps2 = Lists.newArrayList(
+ "namespace:3?module=module3&revision=2012-12-12",
+ "namespace:4?module=module4&revision=2012-12-12",
+ "randomNonModuleCap"
+ );
+ final NetconfSessionCapabilities sessionCaps2 = NetconfSessionCapabilities.fromStrings(caps2);
+ assertCaps(sessionCaps2, 1, 2);
+
+ final NetconfSessionCapabilities merged = sessionCaps1.replaceModuleCaps(sessionCaps2);
+ assertCaps(merged, 2, 2 + 1 /*Preserved monitoring*/);
+ for (final QName qName : sessionCaps2.getModuleBasedCaps()) {
+ assertThat(merged.getModuleBasedCaps(), JUnitMatchers.hasItem(qName));
+ }
+ assertThat(merged.getModuleBasedCaps(), JUnitMatchers.hasItem(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING));
+
+ assertThat(merged.getNonModuleCaps(), JUnitMatchers.hasItem("urn:ietf:params:netconf:base:1.0"));
+ assertThat(merged.getNonModuleCaps(), JUnitMatchers.hasItem("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
+ }
+
+ private void assertCaps(final NetconfSessionCapabilities sessionCaps1, final int nonModuleCaps, final int moduleCaps) {
+ assertEquals(nonModuleCaps, sessionCaps1.getNonModuleCaps().size());
+ assertEquals(moduleCaps, sessionCaps1.getModuleBasedCaps().size());
+ }
+}
--- /dev/null
+package org.opendaylight.controller.sal.connect.netconf.sal.tx;
+
+import static junit.framework.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.DISCARD_CHANGES_RPC_CONTENT;
+
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
+import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
+import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+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.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
+public class NetconfDeviceWriteOnlyTxTest {
+
+ private final RemoteDeviceId id = new RemoteDeviceId("test-mount");
+
+ @Mock
+ private RpcImplementation rpc;
+ @Mock
+ private DataNormalizer normalizer;
+ private YangInstanceIdentifier yangIId;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+
+ doReturn(Futures.<RpcResult<CompositeNode>>immediateFailedFuture(new IllegalStateException("Failed tx")))
+ .doReturn(Futures.immediateFuture(RpcResultBuilder.<CompositeNode>success().build()))
+ .when(rpc).invokeRpc(any(QName.class), any(CompositeNode.class));
+
+ yangIId = YangInstanceIdentifier.builder().node(QName.create("namespace", "2012-12-12", "name")).build();
+ doReturn(yangIId).when(normalizer).toLegacy(yangIId);
+ }
+
+ @Test
+ public void testDiscardCahnges() {
+ final NetconfDeviceWriteOnlyTx tx = new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, true, true);
+ final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+ try {
+ submitFuture.checkedGet();
+ } catch (final TransactionCommitFailedException e) {
+ // verify discard changes was sent
+ verify(rpc).invokeRpc(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME, DISCARD_CHANGES_RPC_CONTENT);
+ return;
+ }
+
+ fail("Submit should fail");
+ }
+
+
+ @Test
+ public void testDiscardCahngesNotSentWithoutCandidate() {
+ doReturn(Futures.immediateFuture(RpcResultBuilder.<CompositeNode>success().build()))
+ .doReturn(Futures.<RpcResult<CompositeNode>>immediateFailedFuture(new IllegalStateException("Failed tx")))
+ .when(rpc).invokeRpc(any(QName.class), any(CompositeNode.class));
+
+ final NetconfDeviceWriteOnlyTx tx = new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, false, true);
+ tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
+ verify(rpc).invokeRpc(eq(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME), any(CompositeNode.class));
+ verifyNoMoreInteractions(rpc);
+ }
+
+}
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-binding</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft</artifactId>
+ <version>1.1-SNAPSHOT</version>
+ </dependency>
+
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
--- /dev/null
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: CompositeModificationPayload.proto
+
+package org.opendaylight.controller.mdsal;
+
+public final class CompositeModificationPayload {
+ private CompositeModificationPayload() {}
+ public static void registerAllExtensions(
+ com.google.protobuf.ExtensionRegistry registry) {
+ registry.add(org.opendaylight.controller.mdsal.CompositeModificationPayload.modification);
+ }
+ public static final int MODIFICATION_FIELD_NUMBER = 2;
+ /**
+ * <code>extend .org.opendaylight.controller.cluster.raft.AppendEntries.ReplicatedLogEntry.Payload { ... }</code>
+ */
+ public static final
+ com.google.protobuf.GeneratedMessage.GeneratedExtension<
+ org.opendaylight.controller.cluster.raft.protobuff.messages.AppendEntriesMessages.AppendEntries.ReplicatedLogEntry.Payload,
+ org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.CompositeModification> modification = com.google.protobuf.GeneratedMessage
+ .newFileScopedGeneratedExtension(
+ org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.CompositeModification.class,
+ org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.CompositeModification.getDefaultInstance());
+
+ public static com.google.protobuf.Descriptors.FileDescriptor
+ getDescriptor() {
+ return descriptor;
+ }
+ private static com.google.protobuf.Descriptors.FileDescriptor
+ descriptor;
+ static {
+ java.lang.String[] descriptorData = {
+ "\n\"CompositeModificationPayload.proto\022!or" +
+ "g.opendaylight.controller.mdsal\032\033AppendE" +
+ "ntriesMessages.proto\032\014Common.proto\032\020Pers" +
+ "istent.proto:\242\001\n\014modification\022R.org.open" +
+ "daylight.controller.cluster.raft.AppendE" +
+ "ntries.ReplicatedLogEntry.Payload\030\002 \001(\0132" +
+ "8.org.opendaylight.controller.mdsal.Comp" +
+ "ositeModification"
+ };
+ com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
+ new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
+ public com.google.protobuf.ExtensionRegistry assignDescriptors(
+ com.google.protobuf.Descriptors.FileDescriptor root) {
+ descriptor = root;
+ modification.internalInit(descriptor.getExtensions().get(0));
+ return null;
+ }
+ };
+ com.google.protobuf.Descriptors.FileDescriptor
+ .internalBuildGeneratedFileFrom(descriptorData,
+ new com.google.protobuf.Descriptors.FileDescriptor[] {
+ org.opendaylight.controller.cluster.raft.protobuff.messages.AppendEntriesMessages.getDescriptor(),
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.getDescriptor(),
+ org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.getDescriptor(),
+ }, assigner);
+ }
+
+ // @@protoc_insertion_point(outer_class_scope)
+}
public final boolean isInitialized() {
if (!hasCanCommit()) {
-
+
return false;
}
return true;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
type_ = b;
public final boolean isInitialized() {
if (!hasName()) {
-
+
return false;
}
return true;
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
type_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
public final boolean isInitialized() {
if (!hasValue()) {
-
+
return false;
}
return true;
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
*/
- java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute>
+ java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute>
getAttributesList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
*/
- java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
+ java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
getAttributesOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
type_ = b;
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
getAttributesOrBuilderList() {
return attributes_;
}
attributesBuilder_ = null;
attributes_ = other.attributes_;
bitField0_ = (bitField0_ & ~0x00000008);
- attributesBuilder_ =
+ attributesBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getAttributesFieldBuilder() : null;
} else {
public final boolean isInitialized() {
if (!hasValue()) {
-
+
return false;
}
if (hasNodeType()) {
if (!getNodeType().isInitialized()) {
-
+
return false;
}
}
for (int i = 0; i < getAttributesCount(); i++) {
if (!getAttributes(i).isInitialized()) {
-
+
return false;
}
}
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
type_ = b;
* <code>optional .org.opendaylight.controller.mdsal.QName nodeType = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QName.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.QNameOrBuilder>
getNodeTypeFieldBuilder() {
if (nodeTypeBuilder_ == null) {
nodeTypeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
getAttributesOrBuilderList() {
if (attributesBuilder_ != null) {
return attributesBuilder_.getMessageOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
*/
- public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder>
+ public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder>
getAttributesBuilderList() {
return getAttributesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
getAttributesFieldBuilder() {
if (attributesBuilder_ == null) {
attributesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
/**
* <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
*/
- java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument>
+ java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument>
getArgumentsList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
*/
- java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
+ java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
getArgumentsOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
getArgumentsOrBuilderList() {
return arguments_;
}
argumentsBuilder_ = null;
arguments_ = other.arguments_;
bitField0_ = (bitField0_ & ~0x00000001);
- argumentsBuilder_ =
+ argumentsBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getArgumentsFieldBuilder() : null;
} else {
public final boolean isInitialized() {
for (int i = 0; i < getArgumentsCount(); i++) {
if (!getArguments(i).isInitialized()) {
-
+
return false;
}
}
/**
* <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
getArgumentsOrBuilderList() {
if (argumentsBuilder_ != null) {
return argumentsBuilder_.getMessageOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
*/
- public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder>
+ public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder>
getArgumentsBuilderList() {
return getArgumentsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
getArgumentsFieldBuilder() {
if (argumentsBuilder_ == null) {
argumentsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
*/
- java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute>
+ java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute>
getAttributesList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
*/
- java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
+ java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
getAttributesOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
*/
- java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node>
+ java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node>
getChildList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
*/
- java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getChildOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getPathBytes() {
java.lang.Object ref = path_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
path_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
type_ = b;
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
getAttributesOrBuilderList() {
return attributes_;
}
/**
* <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getChildOrBuilderList() {
return child_;
}
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getValueTypeBytes() {
java.lang.Object ref = valueType_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
valueType_ = b;
attributesBuilder_ = null;
attributes_ = other.attributes_;
bitField0_ = (bitField0_ & ~0x00000004);
- attributesBuilder_ =
+ attributesBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getAttributesFieldBuilder() : null;
} else {
childBuilder_ = null;
child_ = other.child_;
bitField0_ = (bitField0_ & ~0x00000008);
- childBuilder_ =
+ childBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getChildFieldBuilder() : null;
} else {
public final boolean isInitialized() {
for (int i = 0; i < getAttributesCount(); i++) {
if (!getAttributes(i).isInitialized()) {
-
+
return false;
}
}
for (int i = 0; i < getChildCount(); i++) {
if (!getChild(i).isInitialized()) {
-
+
return false;
}
}
if (hasInstanceIdentifierValue()) {
if (!getInstanceIdentifierValue().isInitialized()) {
-
+
return false;
}
}
getPathBytes() {
java.lang.Object ref = path_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
path_ = b;
getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
type_ = b;
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
getAttributesOrBuilderList() {
if (attributesBuilder_ != null) {
return attributesBuilder_.getMessageOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
*/
- public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder>
+ public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder>
getAttributesBuilderList() {
return getAttributesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
getAttributesFieldBuilder() {
if (attributesBuilder_ == null) {
attributesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
/**
* <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getChildOrBuilderList() {
if (childBuilder_ != null) {
return childBuilder_.getMessageOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
*/
- public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder>
+ public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder>
getChildBuilderList() {
return getChildFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getChildFieldBuilder() {
if (childBuilder_ == null) {
childBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
getValueTypeBytes() {
java.lang.Object ref = valueType_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
valueType_ = b;
* <code>optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 8;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getInstanceIdentifierValueFieldBuilder() {
if (instanceIdentifierValueBuilder_ == null) {
instanceIdentifierValueBuilder_ = new com.google.protobuf.SingleFieldBuilder<
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getParentPathBytes() {
java.lang.Object ref = parentPath_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
parentPath_ = b;
public final boolean isInitialized() {
if (!hasParentPath()) {
-
+
return false;
}
if (hasNormalizedNode()) {
if (!getNormalizedNode().isInitialized()) {
-
+
return false;
}
}
getParentPathBytes() {
java.lang.Object ref = parentPath_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
parentPath_ = b;
* <code>optional .org.opendaylight.controller.mdsal.Node normalizedNode = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getNormalizedNodeFieldBuilder() {
if (normalizedNodeBuilder_ == null) {
normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
public final boolean isInitialized() {
if (!hasInstanceIdentifierPath()) {
-
+
return false;
}
if (!getInstanceIdentifierPath().isInitialized()) {
-
+
return false;
}
if (hasNormalizedNode()) {
if (!getNormalizedNode().isInitialized()) {
-
+
return false;
}
}
* <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPath = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getInstanceIdentifierPathFieldBuilder() {
if (instanceIdentifierPathBuilder_ == null) {
instanceIdentifierPathBuilder_ = new com.google.protobuf.SingleFieldBuilder<
* <code>optional .org.opendaylight.controller.mdsal.Node normalizedNode = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getNormalizedNodeFieldBuilder() {
if (normalizedNodeBuilder_ == null) {
normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
/**
* <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
*/
- java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry>
+ java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry>
getMapEntriesList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
*/
- java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
+ java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
getMapEntriesOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
getMapEntriesOrBuilderList() {
return mapEntries_;
}
mapEntriesBuilder_ = null;
mapEntries_ = other.mapEntries_;
bitField0_ = (bitField0_ & ~0x00000001);
- mapEntriesBuilder_ =
+ mapEntriesBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getMapEntriesFieldBuilder() : null;
} else {
public final boolean isInitialized() {
for (int i = 0; i < getMapEntriesCount(); i++) {
if (!getMapEntries(i).isInitialized()) {
-
+
return false;
}
}
/**
* <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
getMapEntriesOrBuilderList() {
if (mapEntriesBuilder_ != null) {
return mapEntriesBuilder_.getMessageOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
*/
- public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder>
+ public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder>
getMapEntriesBuilderList() {
return getMapEntriesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
getMapEntriesFieldBuilder() {
if (mapEntriesBuilder_ == null) {
mapEntriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getNodeIdentifierBytes() {
java.lang.Object ref = nodeIdentifier_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
nodeIdentifier_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getXmlStringBytes() {
java.lang.Object ref = xmlString_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
xmlString_ = b;
public final boolean isInitialized() {
if (!hasNodeIdentifier()) {
-
+
return false;
}
if (!hasXmlString()) {
-
+
return false;
}
return true;
getNodeIdentifierBytes() {
java.lang.Object ref = nodeIdentifier_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
nodeIdentifier_ = b;
getXmlStringBytes() {
java.lang.Object ref = xmlString_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
xmlString_ = b;
/**
* <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
*/
- java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier>
+ java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier>
getRemovedPathsList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
*/
- java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getRemovedPathsOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getRemovedPathsOrBuilderList() {
return removedPaths_;
}
removedPathsBuilder_ = null;
removedPaths_ = other.removedPaths_;
bitField0_ = (bitField0_ & ~0x00000020);
- removedPathsBuilder_ =
+ removedPathsBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getRemovedPathsFieldBuilder() : null;
} else {
public final boolean isInitialized() {
if (hasOriginalSubTree()) {
if (!getOriginalSubTree().isInitialized()) {
-
+
return false;
}
}
if (hasUpdatedSubTree()) {
if (!getUpdatedSubTree().isInitialized()) {
-
+
return false;
}
}
if (hasOriginalData()) {
if (!getOriginalData().isInitialized()) {
-
+
return false;
}
}
if (hasUpdatedData()) {
if (!getUpdatedData().isInitialized()) {
-
+
return false;
}
}
if (hasCreatedData()) {
if (!getCreatedData().isInitialized()) {
-
+
return false;
}
}
for (int i = 0; i < getRemovedPathsCount(); i++) {
if (!getRemovedPaths(i).isInitialized()) {
-
+
return false;
}
}
* <code>optional .org.opendaylight.controller.mdsal.Node originalSubTree = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getOriginalSubTreeFieldBuilder() {
if (originalSubTreeBuilder_ == null) {
originalSubTreeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
* <code>optional .org.opendaylight.controller.mdsal.Node updatedSubTree = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getUpdatedSubTreeFieldBuilder() {
if (updatedSubTreeBuilder_ == null) {
updatedSubTreeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
* <code>optional .org.opendaylight.controller.mdsal.NodeMap originalData = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
getOriginalDataFieldBuilder() {
if (originalDataBuilder_ == null) {
originalDataBuilder_ = new com.google.protobuf.SingleFieldBuilder<
* <code>optional .org.opendaylight.controller.mdsal.NodeMap updatedData = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
getUpdatedDataFieldBuilder() {
if (updatedDataBuilder_ == null) {
updatedDataBuilder_ = new com.google.protobuf.SingleFieldBuilder<
* <code>optional .org.opendaylight.controller.mdsal.NodeMap createdData = 5;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
getCreatedDataFieldBuilder() {
if (createdDataBuilder_ == null) {
createdDataBuilder_ = new com.google.protobuf.SingleFieldBuilder<
/**
* <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getRemovedPathsOrBuilderList() {
if (removedPathsBuilder_ != null) {
return removedPathsBuilder_.getMessageOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
*/
- public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder>
+ public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder>
getRemovedPathsBuilderList() {
return getRemovedPathsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getRemovedPathsFieldBuilder() {
if (removedPathsBuilder_ == null) {
removedPathsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
type_ = b;
public final boolean isInitialized() {
if (!hasType()) {
-
+
return false;
}
if (!hasPath()) {
-
+
return false;
}
if (!getPath().isInitialized()) {
-
+
return false;
}
if (hasData()) {
if (!getData().isInitialized()) {
-
+
return false;
}
}
getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
type_ = b;
* <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier path = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getPathFieldBuilder() {
if (pathBuilder_ == null) {
pathBuilder_ = new com.google.protobuf.SingleFieldBuilder<
* <code>optional .org.opendaylight.controller.mdsal.Node data = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getDataFieldBuilder() {
if (dataBuilder_ == null) {
dataBuilder_ = new com.google.protobuf.SingleFieldBuilder<
/**
* <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
*/
- java.util.List<org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification>
+ java.util.List<org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification>
getModificationList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
*/
- java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
+ java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
getModificationOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
/**
* <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
getModificationOrBuilderList() {
return modification_;
}
modificationBuilder_ = null;
modification_ = other.modification_;
bitField0_ = (bitField0_ & ~0x00000001);
- modificationBuilder_ =
+ modificationBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getModificationFieldBuilder() : null;
} else {
public final boolean isInitialized() {
for (int i = 0; i < getModificationCount(); i++) {
if (!getModification(i).isInitialized()) {
-
+
return false;
}
}
/**
* <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
*/
- public java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
+ public java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
getModificationOrBuilderList() {
if (modificationBuilder_ != null) {
return modificationBuilder_.getMessageOrBuilderList();
/**
* <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
*/
- public java.util.List<org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder>
+ public java.util.List<org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder>
getModificationBuilderList() {
return getModificationFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
- org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
+ org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
getModificationFieldBuilder() {
if (modificationBuilder_ == null) {
modificationBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
static {
java.lang.String[] descriptorData = {
"\n\020Persistent.proto\022!org.opendaylight.con" +
- "troller.mdsal\032\014Common.proto\"\230\001\n\014Modifica" +
- "tion\022\014\n\004type\030\001 \002(\t\022C\n\004path\030\002 \002(\01325.org.o" +
- "pendaylight.controller.mdsal.InstanceIde" +
- "ntifier\0225\n\004data\030\003 \001(\0132\'.org.opendaylight" +
- ".controller.mdsal.Node\"^\n\025CompositeModif" +
- "ication\022E\n\014modification\030\001 \003(\0132/.org.open" +
- "daylight.controller.mdsal.ModificationBO" +
- "\n9org.opendaylight.controller.protobuff." +
- "messages.persistentB\022PersistentMessages"
+ "troller.mdsal\032\014Common.proto\032\033AppendEntri" +
+ "esMessages.proto\"\230\001\n\014Modification\022\014\n\004typ" +
+ "e\030\001 \002(\t\022C\n\004path\030\002 \002(\01325.org.opendaylight" +
+ ".controller.mdsal.InstanceIdentifier\0225\n\004" +
+ "data\030\003 \001(\0132\'.org.opendaylight.controller" +
+ ".mdsal.Node\"^\n\025CompositeModification\022E\n\014" +
+ "modification\030\001 \003(\0132/.org.opendaylight.co" +
+ "ntroller.mdsal.ModificationBO\n9org.opend" +
+ "aylight.controller.protobuff.messages.pe",
+ "rsistentB\022PersistentMessages"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.getDescriptor(),
+ org.opendaylight.controller.cluster.raft.protobuff.messages.AppendEntriesMessages.getDescriptor(),
}, assigner);
}
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getDataChangeListenerActorPathBytes() {
java.lang.Object ref = dataChangeListenerActorPath_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
dataChangeListenerActorPath_ = b;
public final boolean isInitialized() {
if (!hasInstanceIdentifierPath()) {
-
+
return false;
}
if (!hasDataChangeListenerActorPath()) {
-
+
return false;
}
if (!hasDataChangeScope()) {
-
+
return false;
}
if (!getInstanceIdentifierPath().isInitialized()) {
-
+
return false;
}
return true;
* <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPath = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getInstanceIdentifierPathFieldBuilder() {
if (instanceIdentifierPathBuilder_ == null) {
instanceIdentifierPathBuilder_ = new com.google.protobuf.SingleFieldBuilder<
getDataChangeListenerActorPathBytes() {
java.lang.Object ref = dataChangeListenerActorPath_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
dataChangeListenerActorPath_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getListenerRegistrationPathBytes() {
java.lang.Object ref = listenerRegistrationPath_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
listenerRegistrationPath_ = b;
public final boolean isInitialized() {
if (!hasListenerRegistrationPath()) {
-
+
return false;
}
return true;
getListenerRegistrationPathBytes() {
java.lang.Object ref = listenerRegistrationPath_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
listenerRegistrationPath_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getShardNameBytes() {
java.lang.Object ref = shardName_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
shardName_ = b;
public final boolean isInitialized() {
if (!hasShardName()) {
-
+
return false;
}
return true;
getShardNameBytes() {
java.lang.Object ref = shardName_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
shardName_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getPrimaryPathBytes() {
java.lang.Object ref = primaryPath_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
primaryPath_ = b;
public final boolean isInitialized() {
if (!hasPrimaryPath()) {
-
+
return false;
}
return true;
getPrimaryPathBytes() {
java.lang.Object ref = primaryPath_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
primaryPath_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getShardNameBytes() {
java.lang.Object ref = shardName_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
shardName_ = b;
public final boolean isInitialized() {
if (!hasShardName()) {
-
+
return false;
}
return true;
getShardNameBytes() {
java.lang.Object ref = shardName_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
shardName_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getTransactionChainPathBytes() {
java.lang.Object ref = transactionChainPath_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
transactionChainPath_ = b;
public final boolean isInitialized() {
if (!hasTransactionChainPath()) {
-
+
return false;
}
return true;
getTransactionChainPathBytes() {
java.lang.Object ref = transactionChainPath_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
transactionChainPath_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getTransactionIdBytes() {
java.lang.Object ref = transactionId_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
transactionId_ = b;
public final boolean isInitialized() {
if (!hasTransactionId()) {
-
+
return false;
}
return true;
getTransactionIdBytes() {
java.lang.Object ref = transactionId_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
transactionId_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getTransactionActorPathBytes() {
java.lang.Object ref = transactionActorPath_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
transactionActorPath_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getTransactionIdBytes() {
java.lang.Object ref = transactionId_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
transactionId_ = b;
public final boolean isInitialized() {
if (!hasTransactionActorPath()) {
-
+
return false;
}
if (!hasTransactionId()) {
-
+
return false;
}
return true;
getTransactionActorPathBytes() {
java.lang.Object ref = transactionActorPath_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
transactionActorPath_ = b;
getTransactionIdBytes() {
java.lang.Object ref = transactionId_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
transactionId_ = b;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
- com.google.protobuf.ByteString bs =
+ com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
getActorPathBytes() {
java.lang.Object ref = actorPath_;
if (ref instanceof java.lang.String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actorPath_ = b;
public final boolean isInitialized() {
if (!hasActorPath()) {
-
+
return false;
}
return true;
getActorPathBytes() {
java.lang.Object ref = actorPath_;
if (ref instanceof String) {
- com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
actorPath_ = b;
public final boolean isInitialized() {
if (!hasInstanceIdentifierPathArguments()) {
-
+
return false;
}
if (!getInstanceIdentifierPathArguments().isInitialized()) {
-
+
return false;
}
return true;
* <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getInstanceIdentifierPathArgumentsFieldBuilder() {
if (instanceIdentifierPathArgumentsBuilder_ == null) {
instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder<
public final boolean isInitialized() {
if (!hasInstanceIdentifierPathArguments()) {
-
+
return false;
}
if (!getInstanceIdentifierPathArguments().isInitialized()) {
-
+
return false;
}
return true;
* <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getInstanceIdentifierPathArgumentsFieldBuilder() {
if (instanceIdentifierPathArgumentsBuilder_ == null) {
instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder<
public final boolean isInitialized() {
if (hasNormalizedNode()) {
if (!getNormalizedNode().isInitialized()) {
-
+
return false;
}
}
* <code>optional .org.opendaylight.controller.mdsal.Node normalizedNode = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getNormalizedNodeFieldBuilder() {
if (normalizedNodeBuilder_ == null) {
normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
public final boolean isInitialized() {
if (!hasInstanceIdentifierPathArguments()) {
-
+
return false;
}
if (!hasNormalizedNode()) {
-
+
return false;
}
if (!getInstanceIdentifierPathArguments().isInitialized()) {
-
+
return false;
}
if (!getNormalizedNode().isInitialized()) {
-
+
return false;
}
return true;
* <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getInstanceIdentifierPathArgumentsFieldBuilder() {
if (instanceIdentifierPathArgumentsBuilder_ == null) {
instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder<
* <code>required .org.opendaylight.controller.mdsal.Node normalizedNode = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getNormalizedNodeFieldBuilder() {
if (normalizedNodeBuilder_ == null) {
normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
public final boolean isInitialized() {
if (!hasInstanceIdentifierPathArguments()) {
-
+
return false;
}
if (!hasNormalizedNode()) {
-
+
return false;
}
if (!getInstanceIdentifierPathArguments().isInitialized()) {
-
+
return false;
}
if (!getNormalizedNode().isInitialized()) {
-
+
return false;
}
return true;
* <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
getInstanceIdentifierPathArgumentsFieldBuilder() {
if (instanceIdentifierPathArgumentsBuilder_ == null) {
instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder<
* <code>required .org.opendaylight.controller.mdsal.Node normalizedNode = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
- org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
+ org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
getNormalizedNodeFieldBuilder() {
if (normalizedNodeBuilder_ == null) {
normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
--- /dev/null
+package org.opendaylight.controller.mdsal;
+
+import "AppendEntriesMessages.proto";
+import "Common.proto";
+import "Persistent.proto";
+
+extend org.opendaylight.controller.cluster.raft.AppendEntries.ReplicatedLogEntry.Payload {
+ optional CompositeModification modification=2;
+}
+
+
package org.opendaylight.controller.mdsal;
import "Common.proto";
+import "AppendEntriesMessages.proto";
option java_package = "org.opendaylight.controller.protobuff.messages.persistent";
option java_outer_classname = "PersistentMessages";
message CompositeModification {
repeated Modification modification=1;
}
+
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-util</artifactId>
</dependency>
-
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-core-spi</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-common-impl</artifactId>
+ </dependency>
<!-- Yang tools-->
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-api</artifactId>
+
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-api</artifactId>
+
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-impl</artifactId>
+
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-common</artifactId>
+
</dependency>
<version>${slf4j.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-parser-impl</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.collections</groupId>
+ <artifactId>google-collections</artifactId>
+ <version>1.0</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
import org.opendaylight.controller.remote.rpc.RemoteRpcProviderFactory;
import org.opendaylight.controller.sal.core.api.Broker;
-import org.osgi.framework.BundleContext;
public class RemoteRPCBrokerModule extends org.opendaylight.controller.config.yang.config.remote_rpc_connector.AbstractRemoteRPCBrokerModule {
- private BundleContext bundleContext;
public RemoteRPCBrokerModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
@Override
public java.lang.AutoCloseable createInstance() {
Broker broker = getDomBrokerDependency();
- return RemoteRpcProviderFactory.createInstance(broker, bundleContext);
- }
-
- public void setBundleContext(final BundleContext bundleContext) {
- this.bundleContext = bundleContext;
+ return RemoteRpcProviderFactory.createInstance(broker);
}
}
*/
package org.opendaylight.controller.config.yang.config.remote_rpc_connector;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.Module;
-import org.osgi.framework.BundleContext;
public class RemoteRPCBrokerModuleFactory extends org.opendaylight.controller.config.yang.config.remote_rpc_connector.AbstractRemoteRPCBrokerModuleFactory {
- @Override
- public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) {
- RemoteRPCBrokerModule module = (RemoteRPCBrokerModule)super.createModule(instanceName,dependencyResolver,bundleContext);
- module.setBundleContext(bundleContext);
- return module;
- }
-
- @Override
- public Module createModule(String instanceName, DependencyResolver dependencyResolver,
- DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception {
- RemoteRPCBrokerModule module = (RemoteRPCBrokerModule)super.createModule(instanceName, dependencyResolver,
- old, bundleContext);
- module.setBundleContext(bundleContext);
- return module;
- }
-
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.remote.rpc;
+
+
+public class ActorConstants {
+ public static final String RPC_BROKER = "rpc-broker";
+ public static final String RPC_REGISTRY = "rpc-registry";
+ public static final String RPC_MANAGER = "rpc";
+
+ public static final String RPC_BROKER_PATH= "/user/rpc/rpc-broker";
+ public static final String RPC_REGISTRY_PATH = "/user/rpc/rpc-registry";
+}
import org.opendaylight.controller.remote.rpc.messages.InvokeRoutedRpc;
import org.opendaylight.controller.remote.rpc.messages.InvokeRpc;
import org.opendaylight.controller.remote.rpc.messages.RpcResponse;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.common.util.Rpcs;
+import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
+import org.opendaylight.controller.remote.rpc.utils.XmlUtils;
import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation;
import org.opendaylight.controller.sal.core.api.RpcImplementation;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.ArrayList;
-import java.util.Collection;
import java.util.Collections;
import java.util.Set;
}
@Override
- public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, InstanceIdentifier identifier, CompositeNode input) {
+ public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, YangInstanceIdentifier identifier, CompositeNode input) {
InvokeRoutedRpc rpcMsg = new InvokeRoutedRpc(rpc, identifier, input);
return executeMsg(rpcMsg);
}
private ListenableFuture<RpcResult<CompositeNode>> executeMsg(Object rpcMsg) {
- CompositeNode result = null;
- Collection<RpcError> errors = errors = new ArrayList<>();
+ ListenableFuture<RpcResult<CompositeNode>> listenableFuture = null;
+
try {
Object response = ActorUtil.executeLocalOperation(rpcBroker, rpcMsg, ActorUtil.ASK_DURATION, ActorUtil.AWAIT_DURATION);
if(response instanceof RpcResponse) {
+
RpcResponse rpcResponse = (RpcResponse) response;
- result = XmlUtils.xmlToCompositeNode(rpcResponse.getResultCompositeNode());
+ CompositeNode result = XmlUtils.xmlToCompositeNode(rpcResponse.getResultCompositeNode());
+ listenableFuture = Futures.immediateFuture(RpcResultBuilder.success(result).build());
+
} else if(response instanceof ErrorResponse) {
+
ErrorResponse errorResponse = (ErrorResponse) response;
Exception e = errorResponse.getException();
- errors.add(RpcErrors.getRpcError(null, null, null, null, e.getMessage(), null, e.getCause()));
+ final RpcResultBuilder<CompositeNode> failed = RpcResultBuilder.failed();
+ failed.withError(null, null, e.getMessage(), null, null, e.getCause());
+ listenableFuture = Futures.immediateFuture(failed.build());
+
}
} catch (Exception e) {
LOG.error("Error occurred while invoking RPC actor {}", e.toString());
- errors.add(RpcErrors.getRpcError(null, null, null, null, e.getMessage(), null, e.getCause()));
+
+ final RpcResultBuilder<CompositeNode> failed = RpcResultBuilder.failed();
+ failed.withError(null, null, e.getMessage(), null, null, e.getCause());
+ listenableFuture = Futures.immediateFuture(failed.build());
}
- return Futures.immediateFuture(Rpcs.getRpcResult(true, result, errors));
+
+ return listenableFuture;
}
}
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
+import org.opendaylight.controller.remote.rpc.messages.UpdateSchemaContext;
import org.opendaylight.controller.remote.rpc.registry.ClusterWrapper;
import org.opendaylight.controller.remote.rpc.registry.ClusterWrapperImpl;
-import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.controller.sal.core.api.Provider;
import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
-import java.util.Set;
/**
* This is the base class which initialize all the actors, listeners and
* default RPc implementation so remote invocation of rpcs.
*/
-public class RemoteRpcProvider implements AutoCloseable, Provider{
+public class RemoteRpcProvider implements AutoCloseable, Provider, SchemaContextListener {
private static final Logger LOG = LoggerFactory.getLogger(RemoteRpcProvider.class);
private final ActorSystem actorSystem;
- private ActorRef rpcBroker;
- private ActorRef rpcRegistry;
private final RpcProvisionRegistry rpcProvisionRegistry;
private Broker.ProviderSession brokerSession;
- private RpcListener rpcListener;
- private RoutedRpcListener routeChangeListener;
- private RemoteRpcImplementation rpcImplementation;
+ private SchemaContext schemaContext;
+ private ActorRef rpcManager;
+
+
public RemoteRpcProvider(ActorSystem actorSystem, RpcProvisionRegistry rpcProvisionRegistry) {
this.actorSystem = actorSystem;
this.rpcProvisionRegistry = rpcProvisionRegistry;
@Override
public void close() throws Exception {
this.actorSystem.shutdown();
- unregisterSupportedRpcs();
- unregisterSupportedRoutedRpcs();
}
@Override
}
private void start() {
- LOG.debug("Starting all rpc listeners.");
+ LOG.info("Starting all rpc listeners and actors.");
// Create actor to handle and sync routing table in cluster
ClusterWrapper clusterWrapper = new ClusterWrapperImpl(actorSystem);
- rpcRegistry = actorSystem.actorOf(RpcRegistry.props(clusterWrapper), "rpc-registry");
-
- // Create actor to invoke and execute rpc
SchemaService schemaService = brokerSession.getService(SchemaService.class);
- SchemaContext schemaContext = schemaService.getGlobalContext();
- rpcBroker = actorSystem.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), "rpc-broker");
- String rpcBrokerPath = clusterWrapper.getAddress().toString() + "/user/rpc-broker";
- rpcListener = new RpcListener(rpcRegistry, rpcBrokerPath);
- routeChangeListener = new RoutedRpcListener(rpcRegistry, rpcBrokerPath);
- rpcImplementation = new RemoteRpcImplementation(rpcBroker, schemaContext);
- brokerSession.addRpcRegistrationListener(rpcListener);
- rpcProvisionRegistry.registerRouteChangeListener(routeChangeListener);
- rpcProvisionRegistry.setRoutedRpcDefaultDelegate(rpcImplementation);
- announceSupportedRpcs();
- announceSupportedRoutedRpcs();
+ schemaContext = schemaService.getGlobalContext();
- }
+ rpcManager = actorSystem.actorOf(RpcManager.props(clusterWrapper, schemaContext, brokerSession, rpcProvisionRegistry), ActorConstants.RPC_MANAGER);
- /**
- * Add all the locally registered RPCs in the clustered routing table
- */
- private void announceSupportedRpcs(){
- LOG.debug("Adding all supported rpcs to routing table");
- Set<QName> currentlySupported = brokerSession.getSupportedRpcs();
- for (QName rpc : currentlySupported) {
- rpcListener.onRpcImplementationAdded(rpc);
- }
+ LOG.debug("Rpc actors are created.");
}
- /**
- * Add all the locally registered Routed RPCs in the clustered routing table
- */
- private void announceSupportedRoutedRpcs(){
-
- //TODO: announce all routed RPCs as well
- }
-
- /**
- * Un-Register all the supported RPCs from clustered routing table
- */
- private void unregisterSupportedRpcs(){
- LOG.debug("removing all supported rpcs to routing table");
- Set<QName> currentlySupported = brokerSession.getSupportedRpcs();
- for (QName rpc : currentlySupported) {
- rpcListener.onRpcImplementationRemoved(rpc);
- }
- }
-
- /**
- * Un-Register all the locally supported Routed RPCs from clustered routing table
- */
- private void unregisterSupportedRoutedRpcs(){
-
- //TODO: remove all routed RPCs as well
+ @Override
+ public void onGlobalContextUpdated(SchemaContext schemaContext) {
+ this.schemaContext = schemaContext;
+ rpcManager.tell(new UpdateSchemaContext(schemaContext), null);
}
}
import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
-import org.osgi.framework.BundleContext;
public class RemoteRpcProviderFactory {
- public static RemoteRpcProvider createInstance(final Broker broker, final BundleContext bundleContext){
+ public static RemoteRpcProvider createInstance(final Broker broker){
RemoteRpcProvider rpcProvider =
new RemoteRpcProvider(ActorSystemFactory.getInstance(), (RpcProvisionRegistry) broker);
- broker.registerProvider(rpcProvider, bundleContext);
+ broker.registerProvider(rpcProvider);
return rpcProvider;
}
}
*/
package org.opendaylight.controller.remote.rpc;
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.sal.connector.api.RpcRouter;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
import java.io.Serializable;
-public class RouteIdentifierImpl implements RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier>,Serializable {
+public class RouteIdentifierImpl implements RpcRouter.RouteIdentifier<QName, QName, YangInstanceIdentifier>,Serializable {
private static final long serialVersionUID = 1L;
- private QName context;
- private QName type;
- private InstanceIdentifier route;
+ private final QName context;
+ private final QName type;
+ private final YangInstanceIdentifier route;
- public RouteIdentifierImpl(QName context, QName type, InstanceIdentifier route) {
+ public RouteIdentifierImpl(final QName context, final QName type, final YangInstanceIdentifier route) {
+ Preconditions.checkNotNull(type, "Rpc type should not be null");
this.context = context;
this.type = type;
this.route = route;
}
@Override
- public InstanceIdentifier getRoute() {
+ public YangInstanceIdentifier getRoute() {
return this.route;
}
import akka.actor.ActorRef;
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.remote.rpc.messages.AddRoutedRpc;
import org.opendaylight.controller.remote.rpc.messages.RemoveRoutedRpc;
+import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
import org.opendaylight.controller.sal.connector.api.RpcRouter;
import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Set;
-public class RoutedRpcListener implements RouteChangeListener<RpcRoutingContext, InstanceIdentifier>{
+public class RoutedRpcListener implements RouteChangeListener<RpcRoutingContext, YangInstanceIdentifier>{
private static final Logger LOG = LoggerFactory.getLogger(RoutedRpcListener.class);
private final ActorRef rpcRegistry;
private final String actorPath;
public RoutedRpcListener(ActorRef rpcRegistry, String actorPath) {
+ Preconditions.checkNotNull(rpcRegistry, "rpc registry actor should not be null");
+ Preconditions.checkNotNull(actorPath, "actor path of rpc broker on current node should not be null");
+
this.rpcRegistry = rpcRegistry;
this.actorPath = actorPath;
}
@Override
- public void onRouteChange(RouteChange<RpcRoutingContext, InstanceIdentifier> routeChange) {
- Map<RpcRoutingContext, Set<InstanceIdentifier>> announcements = routeChange.getAnnouncements();
+ public void onRouteChange(RouteChange<RpcRoutingContext, YangInstanceIdentifier> routeChange) {
+ Map<RpcRoutingContext, Set<YangInstanceIdentifier>> announcements = routeChange.getAnnouncements();
announce(getRouteIdentifiers(announcements));
- Map<RpcRoutingContext, Set<InstanceIdentifier>> removals = routeChange.getRemovals();
+ Map<RpcRoutingContext, Set<YangInstanceIdentifier>> removals = routeChange.getRemovals();
remove(getRouteIdentifiers(removals));
}
* @param changes
* @return
*/
- private Set<RpcRouter.RouteIdentifier<?, ?, ?>> getRouteIdentifiers(Map<RpcRoutingContext, Set<InstanceIdentifier>> changes) {
+ private Set<RpcRouter.RouteIdentifier<?, ?, ?>> getRouteIdentifiers(Map<RpcRoutingContext, Set<YangInstanceIdentifier>> changes) {
RouteIdentifierImpl routeId = null;
Set<RpcRouter.RouteIdentifier<?, ?, ?>> routeIdSet = new HashSet<>();
for (RpcRoutingContext context : changes.keySet()){
- for (InstanceIdentifier instanceId : changes.get(context)){
+ for (YangInstanceIdentifier instanceId : changes.get(context)){
routeId = new RouteIdentifierImpl(null, context.getRpc(), instanceId);
routeIdSet.add(routeId);
}
import org.opendaylight.controller.remote.rpc.messages.InvokeRoutedRpc;
import org.opendaylight.controller.remote.rpc.messages.InvokeRpc;
import org.opendaylight.controller.remote.rpc.messages.RpcResponse;
+import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
+import org.opendaylight.controller.remote.rpc.utils.XmlUtils;
import org.opendaylight.controller.sal.core.api.Broker;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
private static final Logger LOG = LoggerFactory.getLogger(RpcBroker.class);
private final Broker.ProviderSession brokerSession;
private final ActorRef rpcRegistry;
- private final SchemaContext schemaContext;
+ private SchemaContext schemaContext;
private RpcBroker(Broker.ProviderSession brokerSession, ActorRef rpcRegistry, SchemaContext schemaContext){
this.brokerSession = brokerSession;
try {
RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, msg.getRpc(), msg.getIdentifier());
GetRoutedRpc routedRpcMsg = new GetRoutedRpc(routeId);
- GetRoutedRpcReply rpcReply = (GetRoutedRpcReply)ActorUtil.executeLocalOperation(rpcRegistry, routedRpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
+ GetRoutedRpcReply rpcReply = (GetRoutedRpcReply) ActorUtil.executeLocalOperation(rpcRegistry, routedRpcMsg, ActorUtil.LOCAL_ASK_DURATION, ActorUtil.LOCAL_AWAIT_DURATION);
String remoteActorPath = rpcReply.getRoutePath();
if(remoteActorPath == null) {
String remoteActorPath = rpcReply.getRoutePath();
if(remoteActorPath == null) {
- LOG.debug("No remote actor found for rpc execution.");
+ LOG.debug("No remote actor found for rpc {{}}.", msg.getRpc());
getSender().tell(new ErrorResponse(
- new IllegalStateException("No remote actor found for rpc execution.")), self());
+ new IllegalStateException("No remote actor found for rpc execution of : " + msg.getRpc())), self());
} else {
+
ExecuteRpc executeMsg = new ExecuteRpc(XmlUtils.inputCompositeNodeToXml(msg.getInput(), schemaContext), msg.getRpc());
Object operationRes = ActorUtil.executeRemoteOperation(this.context().actorSelection(remoteActorPath),
executeMsg, ActorUtil.REMOTE_ASK_DURATION, ActorUtil.REMOTE_AWAIT_DURATION);
try {
Future<RpcResult<CompositeNode>> rpc = brokerSession.rpc(msg.getRpc(), XmlUtils.inputXmlToCompositeNode(msg.getRpc(), msg.getInputCompositeNode(), schemaContext));
RpcResult<CompositeNode> rpcResult = rpc != null ? rpc.get():null;
-
CompositeNode result = rpcResult != null ? rpcResult.getResult() : null;
getSender().tell(new RpcResponse(XmlUtils.outputCompositeNodeToXml(result, schemaContext)), self());
} catch (Exception e) {
import akka.actor.ActorRef;
import org.opendaylight.controller.remote.rpc.messages.AddRpc;
import org.opendaylight.controller.remote.rpc.messages.RemoveRpc;
+import org.opendaylight.controller.remote.rpc.utils.ActorUtil;
import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
import org.opendaylight.yangtools.yang.common.QName;
import org.slf4j.Logger;
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.remote.rpc;
+
+
+import akka.actor.ActorRef;
+import akka.actor.OneForOneStrategy;
+import akka.actor.Props;
+import akka.actor.SupervisorStrategy;
+import akka.japi.Creator;
+import akka.japi.Function;
+import org.opendaylight.controller.remote.rpc.messages.UpdateSchemaContext;
+import org.opendaylight.controller.remote.rpc.registry.ClusterWrapper;
+import org.opendaylight.controller.remote.rpc.registry.RpcRegistry;
+import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+import java.util.Set;
+
+/**
+ * This class acts as a supervisor, creates all the actors, resumes them, if an exception is thrown.
+ *
+ * It also starts the rpc listeners
+ */
+
+public class RpcManager extends AbstractUntypedActor {
+
+ private static final Logger LOG = LoggerFactory.getLogger(RpcManager.class);
+
+ private SchemaContext schemaContext;
+ private final ClusterWrapper clusterWrapper;
+ private ActorRef rpcBroker;
+ private ActorRef rpcRegistry;
+ private final Broker.ProviderSession brokerSession;
+ private RpcListener rpcListener;
+ private RoutedRpcListener routeChangeListener;
+ private RemoteRpcImplementation rpcImplementation;
+ private final RpcProvisionRegistry rpcProvisionRegistry;
+
+ private RpcManager(ClusterWrapper clusterWrapper, SchemaContext schemaContext,
+ Broker.ProviderSession brokerSession, RpcProvisionRegistry rpcProvisionRegistry) {
+ this.clusterWrapper = clusterWrapper;
+ this.schemaContext = schemaContext;
+ this.brokerSession = brokerSession;
+ this.rpcProvisionRegistry = rpcProvisionRegistry;
+
+ createRpcActors();
+ startListeners();
+ }
+
+
+ public static Props props(final ClusterWrapper clusterWrapper, final SchemaContext schemaContext,
+ final Broker.ProviderSession brokerSession, final RpcProvisionRegistry rpcProvisionRegistry) {
+ return Props.create(new Creator<RpcManager>() {
+ @Override
+ public RpcManager create() throws Exception {
+ return new RpcManager(clusterWrapper, schemaContext, brokerSession, rpcProvisionRegistry);
+ }
+ });
+ }
+
+ private void createRpcActors() {
+ LOG.debug("Create rpc registry and broker actors");
+
+ rpcRegistry = getContext().actorOf(RpcRegistry.props(clusterWrapper), ActorConstants.RPC_REGISTRY);
+ rpcBroker = getContext().actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), ActorConstants.RPC_BROKER);
+ }
+
+ private void startListeners() {
+ LOG.debug("Registers rpc listeners");
+
+ String rpcBrokerPath = clusterWrapper.getAddress().toString() + ActorConstants.RPC_BROKER_PATH;
+ rpcListener = new RpcListener(rpcRegistry, rpcBrokerPath);
+ routeChangeListener = new RoutedRpcListener(rpcRegistry, rpcBrokerPath);
+ rpcImplementation = new RemoteRpcImplementation(rpcBroker, schemaContext);
+
+ brokerSession.addRpcRegistrationListener(rpcListener);
+ rpcProvisionRegistry.registerRouteChangeListener(routeChangeListener);
+ rpcProvisionRegistry.setRoutedRpcDefaultDelegate(rpcImplementation);
+ announceSupportedRpcs();
+ }
+
+ /**
+ * Add all the locally registered RPCs in the clustered routing table
+ */
+ private void announceSupportedRpcs(){
+ LOG.debug("Adding all supported rpcs to routing table");
+ Set<QName> currentlySupported = brokerSession.getSupportedRpcs();
+ for (QName rpc : currentlySupported) {
+ rpcListener.onRpcImplementationAdded(rpc);
+ }
+ }
+
+
+ @Override
+ protected void handleReceive(Object message) throws Exception {
+ if(message instanceof UpdateSchemaContext) {
+ updateSchemaContext((UpdateSchemaContext) message);
+ }
+
+ }
+
+ private void updateSchemaContext(UpdateSchemaContext message) {
+ this.schemaContext = message.getSchemaContext();
+ }
+
+ @Override
+ public SupervisorStrategy supervisorStrategy() {
+ return new OneForOneStrategy(10, Duration.create("1 minute"),
+ new Function<Throwable, SupervisorStrategy.Directive>() {
+ @Override
+ public SupervisorStrategy.Directive apply(Throwable t) {
+ return SupervisorStrategy.resume();
+ }
+ }
+ );
+ }
+}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.remote.rpc;
-
-import com.google.common.base.Optional;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-import javax.activation.UnsupportedDataTypeException;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.Set;
-
-public class XmlUtils {
-
- private static final Logger LOG = LoggerFactory.getLogger(XmlUtils.class);
-
- public static String inputCompositeNodeToXml(CompositeNode cNode, SchemaContext schemaContext){
- if (cNode == null) return new String();
-
- //Document domTree = NodeUtils.buildShadowDomTree(cNode);
- Document domTree = null;
- try {
- Set<RpcDefinition> rpcs = schemaContext.getOperations();
- for(RpcDefinition rpc : rpcs) {
- if(rpc.getQName().equals(cNode.getNodeType())){
- domTree = XmlDocumentUtils.toDocument(cNode, rpc.getInput(), XmlDocumentUtils.defaultValueCodecProvider());
- break;
- }
- }
-
- } catch (UnsupportedDataTypeException e) {
- LOG.error("Error during translation of CompositeNode to Document", e);
- }
- return domTransformer(domTree);
- }
-
- public static String outputCompositeNodeToXml(CompositeNode cNode, SchemaContext schemaContext){
- if (cNode == null) return new String();
-
- //Document domTree = NodeUtils.buildShadowDomTree(cNode);
- Document domTree = null;
- try {
- Set<RpcDefinition> rpcs = schemaContext.getOperations();
- for(RpcDefinition rpc : rpcs) {
- if(rpc.getQName().equals(cNode.getNodeType())){
- domTree = XmlDocumentUtils.toDocument(cNode, rpc.getInput(), XmlDocumentUtils.defaultValueCodecProvider());
- break;
- }
- }
-
- } catch (UnsupportedDataTypeException e) {
- LOG.error("Error during translation of CompositeNode to Document", e);
- }
- return domTransformer(domTree);
- }
-
- private static String domTransformer(Document domTree) {
- StringWriter writer = new StringWriter();
- try {
- TransformerFactory tf = TransformerFactory.newInstance();
- Transformer transformer = tf.newTransformer();
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
- transformer.transform(new DOMSource(domTree), new StreamResult(writer));
- } catch (TransformerException e) {
-
- LOG.error("Error during translation of Document to OutputStream", e);
- }
- LOG.debug("compositeNodeToXml " + writer.toString());
-
- return writer.toString();
- }
-
- public static CompositeNode xmlToCompositeNode(String xml){
- if (xml==null || xml.length()==0) return null;
-
- Node<?> dataTree;
- try {
- dataTree = XmlTreeBuilder.buildDataTree(new ByteArrayInputStream(xml.getBytes()));
- } catch (XMLStreamException e) {
- LOG.error("Error during building data tree from XML", e);
- return null;
- }
- if (dataTree == null) {
- LOG.error("data tree is null");
- return null;
- }
- if (dataTree instanceof SimpleNode) {
- LOG.error("RPC XML was resolved as SimpleNode");
- return null;
- }
- return (CompositeNode) dataTree;
- }
-
- public static CompositeNode inputXmlToCompositeNode(QName rpc, String xml, SchemaContext schemaContext){
- if (xml==null || xml.length()==0) return null;
-
- Node<?> dataTree = null;
- try {
-
- Document doc = XmlUtil.readXmlToDocument(xml);
- LOG.debug("xmlToCompositeNode Document is " + xml );
- Set<RpcDefinition> rpcs = schemaContext.getOperations();
- for(RpcDefinition rpcDef : rpcs) {
- if(rpcDef.getQName().equals(rpc)){
- dataTree = XmlDocumentUtils.toDomNode(doc.getDocumentElement(), Optional.<DataSchemaNode>of(rpcDef.getInput()), Optional.of(XmlDocumentUtils.defaultValueCodecProvider()));
- break;
- }
- }
- } catch (SAXException e) {
- LOG.error("Error during building data tree from XML", e);
- } catch (IOException e) {
- LOG.error("Error during building data tree from XML", e);
- }
-
- LOG.debug("xmlToCompositeNode " + dataTree.toString());
- return (CompositeNode) dataTree;
- }
-}
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.sal.connector.api.RpcRouter;
import java.io.Serializable;
public class AddRoutedRpc implements Serializable {
- Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements;
- String actorPath;
+ private final Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements;
+ private final String actorPath;
+
+ public AddRoutedRpc(final Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements, final String actorPath) {
+ Preconditions.checkNotNull(announcements, "Route identifier should not be null");
+ Preconditions.checkNotNull(actorPath, "Actor path should not be null");
- public AddRoutedRpc(Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements, String actorPath) {
this.announcements = announcements;
this.actorPath = actorPath;
}
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
import java.io.Serializable;
public class AddRpc implements Serializable {
- RouteIdentifierImpl routeId;
- String actorPath;
+ private final RouteIdentifierImpl routeId;
+ private final String actorPath;
+
+ public AddRpc(final RouteIdentifierImpl routeId, final String actorPath) {
+ Preconditions.checkNotNull(routeId, "Route identifier should not be null");
+ Preconditions.checkNotNull(actorPath, "Actor path should not be null");
- public AddRpc(RouteIdentifierImpl routeId, String actorPath) {
this.routeId = routeId;
this.actorPath = actorPath;
}
*/
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
+
import java.io.Serializable;
public class ErrorResponse implements Serializable {
- Exception exception;
+ private final Exception exception;
- public ErrorResponse(Exception e) {
+ public ErrorResponse(final Exception e) {
+ Preconditions.checkNotNull(e, "Exception should be present for error message");
this.exception = e;
}
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.yangtools.yang.common.QName;
import java.io.Serializable;
public class ExecuteRpc implements Serializable {
- private String inputCompositeNode;
- private QName rpc;
+ private final String inputCompositeNode;
+ private final QName rpc;
+
+ public ExecuteRpc(final String inputCompositeNode, final QName rpc) {
+ Preconditions.checkNotNull(inputCompositeNode, "Composite Node input string should be present");
+ Preconditions.checkNotNull(rpc, "rpc Qname should not be null");
- public ExecuteRpc(String inputCompositeNode, QName rpc) {
this.inputCompositeNode = inputCompositeNode;
this.rpc = rpc;
}
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
import java.io.Serializable;
public class GetRoutedRpc implements Serializable {
- RouteIdentifierImpl routeId;
+ private final RouteIdentifierImpl routeId;
- public GetRoutedRpc(RouteIdentifierImpl routeId) {
+ public GetRoutedRpc(final RouteIdentifierImpl routeId) {
+ Preconditions.checkNotNull(routeId, "route id should not be null");
this.routeId = routeId;
}
public class GetRoutedRpcReply implements Serializable {
- private String routePath;
+ private final String routePath;
- public GetRoutedRpcReply(String routePath) {
+ public GetRoutedRpcReply(final String routePath) {
this.routePath = routePath;
}
*/
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
import java.io.Serializable;
public class GetRpc implements Serializable {
- RouteIdentifierImpl routeId;
+ private final RouteIdentifierImpl routeId;
- public GetRpc(RouteIdentifierImpl routeId) {
+ public GetRpc(final RouteIdentifierImpl routeId) {
+ Preconditions.checkNotNull(routeId, "Route Id should not be null");
this.routeId = routeId;
}
public class GetRpcReply implements Serializable {
- private String routePath;
+ private final String routePath;
- public GetRpcReply(String routePath) {
+ public GetRpcReply(final String routePath) {
this.routePath = routePath;
}
*/
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import java.io.Serializable;
public class InvokeRoutedRpc implements Serializable {
- private QName rpc;
- private InstanceIdentifier identifier;
- private CompositeNode input;
+ private final QName rpc;
+ private final YangInstanceIdentifier identifier;
+ private final CompositeNode input;
- public InvokeRoutedRpc(QName rpc, InstanceIdentifier identifier, CompositeNode input) {
- this.rpc = rpc;
- this.identifier = identifier;
- this.input = input;
- }
+ public InvokeRoutedRpc(final QName rpc, final YangInstanceIdentifier identifier, final CompositeNode input) {
+ Preconditions.checkNotNull(rpc, "rpc qname should not be null");
+ Preconditions.checkNotNull(identifier, "instance identifier of routed rpc should not be null");
+ Preconditions.checkNotNull(input, "rpc input should not be null");
- public InvokeRoutedRpc(QName rpc, CompositeNode input) {
this.rpc = rpc;
+ this.identifier = identifier;
this.input = input;
}
return rpc;
}
- public InstanceIdentifier getIdentifier() {
+ public YangInstanceIdentifier getIdentifier() {
return identifier;
}
*/
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
public class InvokeRpc implements Serializable {
- private QName rpc;
- private CompositeNode input;
+ private final QName rpc;
+ private final CompositeNode input;
+
+ public InvokeRpc(final QName rpc, final CompositeNode input) {
+ Preconditions.checkNotNull(rpc, "rpc qname should not be null");
+ Preconditions.checkNotNull(input, "rpc input should not be null");
- public InvokeRpc(QName rpc, CompositeNode input) {
this.rpc = rpc;
this.input = input;
}
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.sal.connector.api.RpcRouter;
import java.io.Serializable;
public class RemoveRoutedRpc implements Serializable {
- Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements;
- String actorPath;
+ private final Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements;
+ private final String actorPath;
+
+ public RemoveRoutedRpc(final Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements, final String actorPath) {
+ Preconditions.checkNotNull(announcements, "Route identifier should not be null");
+ Preconditions.checkNotNull(actorPath, "Actor path should not be null");
- public RemoveRoutedRpc(Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements, String actorPath) {
this.announcements = announcements;
this.actorPath = actorPath;
}
package org.opendaylight.controller.remote.rpc.messages;
+import com.google.common.base.Preconditions;
import org.opendaylight.controller.remote.rpc.RouteIdentifierImpl;
import java.io.Serializable;
public class RemoveRpc implements Serializable {
- RouteIdentifierImpl routeId;
+ private final RouteIdentifierImpl routeId;
+
+ public RemoveRpc(final RouteIdentifierImpl routeId) {
+ Preconditions.checkNotNull(routeId, "Route Id should not be null");
- public RemoveRpc(RouteIdentifierImpl routeId) {
this.routeId = routeId;
}
import java.util.Map;
public class RoutingTableData implements Serializable {
- private Map<RpcRouter.RouteIdentifier<?, ?, ?>, String> rpcMap;
- private Map<RpcRouter.RouteIdentifier<?, ?, ?>, LinkedHashSet<String>> routedRpcMap;
+ private final Map<RpcRouter.RouteIdentifier<?, ?, ?>, String> rpcMap;
+ private final Map<RpcRouter.RouteIdentifier<?, ?, ?>, LinkedHashSet<String>> routedRpcMap;
- public RoutingTableData(Map<RpcRouter.RouteIdentifier<?, ?, ?>, String> rpcMap,
- Map<RpcRouter.RouteIdentifier<?, ?, ?>, LinkedHashSet<String>> routedRpcMap) {
+ public RoutingTableData(final Map<RpcRouter.RouteIdentifier<?, ?, ?>, String> rpcMap,
+ final Map<RpcRouter.RouteIdentifier<?, ?, ?>, LinkedHashSet<String>> routedRpcMap) {
this.rpcMap = rpcMap;
this.routedRpcMap = routedRpcMap;
}
import java.io.Serializable;
public class RpcResponse implements Serializable {
- private String resultCompositeNode;
+ private final String resultCompositeNode;
- public RpcResponse(String resultCompositeNode) {
+ public RpcResponse(final String resultCompositeNode) {
this.resultCompositeNode = resultCompositeNode;
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.remote.rpc.messages;
+
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class UpdateSchemaContext {
+
+ private final SchemaContext schemaContext;
+
+ public UpdateSchemaContext(final SchemaContext schemaContext) {
+ this.schemaContext = schemaContext;
+ }
+
+ public SchemaContext getSchemaContext() {
+ return schemaContext;
+ }
+}
import akka.cluster.Member;
import akka.japi.Creator;
import org.opendaylight.controller.remote.rpc.AbstractUntypedActor;
+import org.opendaylight.controller.remote.rpc.ActorConstants;
import org.opendaylight.controller.remote.rpc.messages.AddRoutedRpc;
import org.opendaylight.controller.remote.rpc.messages.AddRpc;
import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpc;
}
if(i == index) {
if(!currentNodeAddress.equals(member.address())) {
- actor = this.context().actorSelection(member.address() + "/user/rpc-registry");
+ actor = this.context().actorSelection(member.address() + ActorConstants.RPC_REGISTRY_PATH);
break;
} else if(index < memberSize-1){ // pick the next element in the set
index++;
i++;
}
if(actor == null && previousMember != null) {
- actor = this.context().actorSelection(previousMember.address() + "/user/rpc-registry");
+ actor = this.context().actorSelection(previousMember.address() + ActorConstants.RPC_REGISTRY_PATH);
}
}
return actor;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
*/
-package org.opendaylight.controller.remote.rpc;
+package org.opendaylight.controller.remote.rpc.utils;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.remote.rpc.utils;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Element;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public final class InstanceIdentifierForXmlCodec {
+ private static final Pattern PREDICATE_PATTERN = Pattern.compile("\\[(.*?)\\]");
+ private static final Splitter SLASH_SPLITTER = Splitter.on('/');
+ private static final Splitter COLON_SPLITTER = Splitter.on(':');
+ private static final Splitter AT_SPLITTER = Splitter.on('@');
+ private static final Logger logger = LoggerFactory.getLogger(InstanceIdentifierForXmlCodec.class);
+
+ private InstanceIdentifierForXmlCodec() {
+ throw new UnsupportedOperationException("Utility class");
+ }
+
+ public static YangInstanceIdentifier deserialize(final Element element, final SchemaContext schemaContext) {
+ Preconditions.checkNotNull(element, "Value of element for deserialization can't be null");
+ Preconditions.checkNotNull(schemaContext,
+ "Schema context for deserialization of instance identifier type can't be null");
+
+ final String valueTrimmed = element.getTextContent().trim();
+ logger.debug("Instance identifier derserialize: splitting the text {} with Slash to find path arguments", valueTrimmed);
+ final Iterator<String> xPathParts = SLASH_SPLITTER.split(valueTrimmed).iterator();
+
+ // must be at least "/pr:node"
+ if (!xPathParts.hasNext() || !xPathParts.next().isEmpty() || !xPathParts.hasNext()) {
+ logger.debug("Instance identifier derserialize: No path argument found for element.");
+ return null;
+ }
+
+ List<PathArgument> result = new ArrayList<>();
+ while (xPathParts.hasNext()) {
+ String xPathPartTrimmed = xPathParts.next().trim();
+
+ PathArgument pathArgument = toPathArgument(xPathPartTrimmed, element, schemaContext);
+ if (pathArgument != null) {
+ result.add(pathArgument);
+ }
+ }
+ return YangInstanceIdentifier.create(result);
+ }
+
+ public static Element serialize(final YangInstanceIdentifier id, final Element element) {
+ Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
+ Preconditions.checkNotNull(element, "DOM element can't be null");
+
+ final RandomPrefix prefixes = new RandomPrefix();
+ final String str = XmlUtils.encodeIdentifier(prefixes, id);
+
+ for (Entry<URI, String> e: prefixes.getPrefixes()) {
+ element.setAttribute("xmlns:" + e.getValue(), e.getKey().toString());
+ }
+ element.setTextContent(str);
+ return element;
+ }
+
+ private static String getIdAndPrefixAsStr(final String pathPart) {
+ int predicateStartIndex = pathPart.indexOf('[');
+ return predicateStartIndex == -1 ? pathPart : pathPart.substring(0, predicateStartIndex);
+ }
+
+ private static PathArgument toPathArgument(final String xPathArgument, final Element element, final SchemaContext schemaContext) {
+ final QName mainQName = toIdentity(xPathArgument, element, schemaContext);
+
+ // predicates
+ final Matcher matcher = PREDICATE_PATTERN.matcher(xPathArgument);
+ final Map<QName, Object> predicates = new HashMap<>();
+ QName currentQName = mainQName;
+
+ while (matcher.find()) {
+ final String predicateStr = matcher.group(1).trim();
+ final int indexOfEqualityMark = predicateStr.indexOf('=');
+ if (indexOfEqualityMark != -1) {
+ final Object predicateValue = toPredicateValue(predicateStr.substring(indexOfEqualityMark + 1));
+ if (predicateValue == null) {
+ return null;
+ }
+
+ if (predicateStr.charAt(0) != '.') {
+ // target is not a leaf-list
+ currentQName = toIdentity(predicateStr.substring(0, indexOfEqualityMark), element, schemaContext);
+ if (currentQName == null) {
+ return null;
+ }
+ }
+ logger.debug("Instance identifier derserialize: finding predicates of node {}", predicateValue);
+ predicates.put(currentQName, predicateValue);
+ }
+ }
+
+ if (predicates.isEmpty()) {
+ return new YangInstanceIdentifier.NodeIdentifier(mainQName);
+ } else {
+ return new YangInstanceIdentifier.NodeIdentifierWithPredicates(mainQName, predicates);
+ }
+
+ }
+
+ public static QName toIdentity(final String xPathArgument, final Element element, final SchemaContext schemaContext) {
+ final String xPathPartTrimmed = getIdAndPrefixAsStr(xPathArgument).trim();
+ final Iterator<String> it = COLON_SPLITTER.split(xPathPartTrimmed).iterator();
+
+ // Empty string
+ if (!it.hasNext()) {
+ return null;
+ }
+
+ final String prefix = it.next().trim();
+ if (prefix.isEmpty()) {
+ return null;
+ }
+
+ // it is not "prefix:value"
+ if (!it.hasNext()) {
+ return null;
+ }
+
+ final String identifier = it.next().trim();
+ if (identifier.isEmpty()) {
+ return null;
+ }
+
+ URI namespace = null;
+ String namespaceStr = null;
+ try {
+ namespaceStr = element.getAttribute("xmlns:"+prefix);
+ namespace = new URI(namespaceStr);
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("It wasn't possible to convert " + namespaceStr + " to URI object.");
+ } catch (NullPointerException e) {
+ throw new IllegalArgumentException("I wasn't possible to get namespace for prefix " + prefix);
+ }
+
+ Module module = schemaContext.findModuleByNamespaceAndRevision(namespace, null);
+ return QName.create(module.getQNameModule(), identifier);
+ }
+
+ private static String trimIfEndIs(final String str, final char end) {
+ final int l = str.length() - 1;
+ if (str.charAt(l) != end) {
+ return null;
+ }
+
+ return str.substring(1, l);
+ }
+
+ private static Object toPredicateValue(final String predicatedValue) {
+ logger.debug("Instance identifier derserialize: converting the predicate vstring to object {}", predicatedValue);
+ final String predicatedValueTrimmed = predicatedValue.trim();
+ if (predicatedValue.isEmpty()) {
+ return null;
+ }
+ String updatedValue = null;
+ switch (predicatedValueTrimmed.charAt(0)) {
+ case '"':
+ updatedValue = trimIfEndIs(predicatedValueTrimmed, '"');
+ break;
+ case '\'':
+ updatedValue = trimIfEndIs(predicatedValueTrimmed, '\'');
+ break;
+ default:
+ updatedValue = predicatedValueTrimmed;
+ }
+ Iterator<String> it = AT_SPLITTER.split(updatedValue).iterator();
+ // Empty string
+ if (!it.hasNext()) {
+ return null;
+ }
+
+ final String value = it.next().trim();
+ if (value.isEmpty()) {
+ return null;
+ }
+
+ if (!it.hasNext()) {
+ return value;
+ }
+
+ final String type = it.next().trim();
+ if (type.isEmpty()) {
+ return value;
+ }
+ Object predicateObject = null;
+ try {
+ logger.debug("Instance identifier derserialize: converting the predicate value {{}}to correct object type {{}}", value, type);
+ predicateObject = Class.forName(type).getConstructor(String.class).newInstance(value);
+ } catch (Exception e) {
+ logger.error("Could not convert to valid type of value", e);
+ }
+ return predicateObject;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.remote.rpc.utils;
+
+import org.opendaylight.yangtools.yang.common.QName;
+
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.ThreadLocalRandom;
+
+/**
+ * Picked from Yang tools because it was not public class
+ */
+
+final class RandomPrefix {
+ final Map<URI, String> prefixes = new HashMap<>();
+
+ Iterable<Entry<URI, String>> getPrefixes() {
+ return prefixes.entrySet();
+ }
+
+ String encodeQName(final QName qname) {
+ String prefix = prefixes.get(qname.getNamespace());
+ if (prefix == null) {
+ prefix = qname.getPrefix();
+ if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
+ final ThreadLocalRandom random = ThreadLocalRandom.current();
+ do {
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 4; i++) {
+ sb.append((char)('a' + random.nextInt(25)));
+ }
+
+ prefix = sb.toString();
+ } while (prefixes.containsValue(prefix));
+ }
+
+ prefixes.put(qname.getNamespace(), prefix);
+ }
+
+ return prefix + ':' + qname.getLocalName();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2013 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.remote.rpc.utils;
+
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
+import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import javax.activation.UnsupportedDataTypeException;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.dom.DOMResult;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import static com.google.common.base.Preconditions.checkState;
+
+public class XmlDocumentUtils {
+ private static class ElementWithSchemaContext {
+ Element element;
+ SchemaContext schemaContext;
+
+ ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
+ this.schemaContext = schemaContext;
+ this.element = element;
+ }
+
+ Element getElement() {
+ return element;
+ }
+
+ SchemaContext getSchemaContext() {
+ return schemaContext;
+ }
+ }
+
+ public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
+ private static final Logger logger = LoggerFactory.getLogger(XmlDocumentUtils.class);
+ private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
+
+ /**
+ * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
+ * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
+ * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
+ * Node Container Schema and transformed accordingly.
+ *
+ * @param data Data DOM root element
+ * @param schema Data Node Container Schema
+ * @param codecProvider XML Codec Provider
+ * @return new instance of XML Document
+ * @throws javax.activation.UnsupportedDataTypeException
+ */
+ public static Document toDocument(final CompositeNode data, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
+ throws UnsupportedDataTypeException {
+ Preconditions.checkNotNull(data);
+ Preconditions.checkNotNull(schema);
+
+ if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
+ throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
+ }
+
+ final DOMResult result = new DOMResult(getDocument());
+ try {
+ final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
+ XmlStreamUtils.create(codecProvider).writeDocument(writer, data, (SchemaNode)schema);
+ writer.close();
+ return (Document)result.getNode();
+ } catch (XMLStreamException e) {
+ logger.error("Failed to serialize data {}", data, e);
+ return null;
+ }
+ }
+
+ public static Document getDocument() {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ Document doc = null;
+ try {
+ DocumentBuilder bob = dbf.newDocumentBuilder();
+ doc = bob.newDocument();
+ } catch (ParserConfigurationException e) {
+ throw new RuntimeException(e);
+ }
+ return doc;
+ }
+
+
+ public static QName qNameFromElement(final Element xmlElement) {
+ String namespace = xmlElement.getNamespaceURI();
+ String localName = xmlElement.getLocalName();
+ return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
+ }
+
+ private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
+ checkQName(xmlElement, schema.getQName());
+ if (schema instanceof DataNodeContainer) {
+ return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, schemaCtx);
+ } else if (schema instanceof LeafSchemaNode) {
+ return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
+ } else if (schema instanceof LeafListSchemaNode) {
+ return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
+ }
+ return null;
+ }
+
+
+
+ private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
+ final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
+ TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
+ String text = xmlElement.getTextContent();
+ Object value = null;
+ if (codec != null) {
+ logger.debug("toSimpleNodeWithType: found codec, deserializing text {}", text);
+ value = codec.deserialize(text);
+ }
+
+ final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(schema.getType());
+ if (baseType instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
+ logger.debug("toSimpleNodeWithType: base type of node is instance identifier, deserializing element", xmlElement);
+ value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
+
+ } else if(baseType instanceof IdentityrefTypeDefinition){
+ logger.debug("toSimpleNodeWithType: base type of node is IdentityrefTypeDefinition, deserializing element", xmlElement);
+ value = InstanceIdentifierForXmlCodec.toIdentity(xmlElement.getTextContent(), xmlElement, schemaCtx);
+
+ }
+
+ if (value == null) {
+ logger.debug("toSimpleNodeWithType: no type found for element, returning just the text string value of element {}", xmlElement);
+ value = xmlElement.getTextContent();
+ }
+
+ Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
+ return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
+ }
+
+ private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
+ final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
+ TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
+ String text = xmlElement.getTextContent();
+ Object value = null;
+ if (codec != null) {
+ logger.debug("toSimpleNodeWithType: found codec, deserializing text {}", text);
+ value = codec.deserialize(text);
+ }
+
+ if (schema.getType() instanceof org.opendaylight.yangtools.yang.model.util.InstanceIdentifier) {
+ logger.debug("toSimpleNodeWithType: base type of node is instance identifier, deserializing element", xmlElement);
+ value = InstanceIdentifierForXmlCodec.deserialize(xmlElement,schemaCtx);
+ }
+
+ if (value == null) {
+ logger.debug("toSimpleNodeWithType: no type found for element, returning just the text string value of element {}", xmlElement);
+ value = xmlElement.getTextContent();
+ }
+
+ Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
+ return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
+ }
+
+ private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
+ final SchemaContext schemaCtx) {
+ List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
+ Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
+ return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
+ }
+
+ private static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
+ Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
+ if(attributeNodeNS == null) {
+ return Optional.absent();
+ }
+
+ ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
+ Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
+
+ return Optional.of(action);
+ }
+
+ private static void checkQName(final Element xmlElement, final QName qName) {
+ checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
+ checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
+ }
+
+ public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Collection<DataSchemaNode> dataSchemaNode) {
+ if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
+ for (DataSchemaNode dsn : dataSchemaNode) {
+ if (qname.isEqualWithoutRevision(dsn.getQName())) {
+ return Optional.<DataSchemaNode> of(dsn);
+ } else if (dsn instanceof ChoiceNode) {
+ for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
+ Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
+ if (foundDsn != null && foundDsn.isPresent()) {
+ return foundDsn;
+ }
+ }
+ }
+ }
+ }
+ return Optional.absent();
+ }
+
+ private static Node<?> toDomNode(Element element) {
+ QName qname = qNameFromElement(element);
+
+ ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
+ NodeList nodes = element.getChildNodes();
+ boolean isSimpleObject = true;
+ String value = null;
+ for (int i = 0; i < nodes.getLength(); i++) {
+ org.w3c.dom.Node child = nodes.item(i);
+ if (child instanceof Element) {
+ isSimpleObject = false;
+ values.add(toDomNode((Element) child));
+ }
+ if (isSimpleObject && child instanceof org.w3c.dom.Text) {
+ value = element.getTextContent();
+ if (!Strings.isNullOrEmpty(value)) {
+ isSimpleObject = true;
+ }
+ }
+ }
+ if (isSimpleObject) {
+ return new SimpleNodeTOImpl<>(qname, null, value);
+ }
+ return ImmutableCompositeNode.create(qname, values.build());
+ }
+
+ public static List<Node<?>> toDomNodes(final Element element, final Optional<Collection<DataSchemaNode>> context,SchemaContext schemaCtx) {
+ return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
+
+ @Override
+ public Optional<Node<?>> apply(ElementWithSchemaContext input) {
+ if (context.isPresent()) {
+ QName partialQName = qNameFromElement(input.getElement());
+ Optional<DataSchemaNode> schemaNode = XmlDocumentUtils.findFirstSchema(partialQName, context.get());
+ if (schemaNode.isPresent()) {
+ return Optional.<Node<?>> fromNullable(//
+ toNodeWithSchema(input.getElement(), schemaNode.get(), XmlDocumentUtils.defaultValueCodecProvider(),input.getSchemaContext()));
+ }
+ }
+ return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
+ }
+
+ });
+
+ }
+
+ private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
+ final int l = nodes.getLength();
+ if (l == 0) {
+ return ImmutableList.of();
+ }
+
+ final List<T> list = new ArrayList<>(l);
+ for (int i = 0; i < l; i++) {
+ org.w3c.dom.Node child = nodes.item(i);
+ if (child instanceof Element) {
+ Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
+ if (result.isPresent()) {
+ list.add(result.get());
+ }
+ }
+ }
+ return ImmutableList.copyOf(list);
+ }
+
+ public static final XmlCodecProvider defaultValueCodecProvider() {
+ return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.remote.rpc.utils;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
+import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+import java.net.URI;
+import java.util.Map.Entry;
+
+/**
+ * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
+ * by no means final and subject to change as more functionality is centralized here.
+ */
+@Beta
+public class XmlStreamUtils {
+ private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
+ private final XmlCodecProvider codecProvider;
+
+ protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
+ this.codecProvider = Preconditions.checkNotNull(codecProvider);
+ }
+
+ /**
+ * Create a new instance encapsulating a particular codec provider.
+ *
+ * @param codecProvider XML codec provider
+ * @return A new instance
+ */
+ public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
+ return new XmlStreamUtils(codecProvider);
+ }
+
+ /**
+ * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
+ * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
+ *
+ * @param data Data node
+ * @return True if the data node will result in empty element body.
+ */
+ public static boolean isEmptyElement(final Node<?> data) {
+ if (data == null) {
+ return true;
+ }
+
+ if (data instanceof CompositeNode) {
+ return ((CompositeNode) data).getValue().isEmpty();
+ }
+ if (data instanceof SimpleNode) {
+ return data.getValue() == null;
+ }
+
+ // Safe default
+ return false;
+ }
+
+ /**
+ * Write an InstanceIdentifier into the output stream. Calling corresponding {@link javax.xml.stream.XMLStreamWriter#writeStartElement(String)}
+ * and {@link javax.xml.stream.XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
+ *
+ * @param writer XML Stream writer
+ * @param id InstanceIdentifier
+ * @throws javax.xml.stream.XMLStreamException
+ */
+ public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
+ Preconditions.checkNotNull(writer, "Writer may not be null");
+ Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
+ LOG.debug("Writing Instance identifier with Random prefix");
+ final RandomPrefix prefixes = new RandomPrefix();
+ final String str = XmlUtils.encodeIdentifier(prefixes, id);
+
+ for (Entry<URI, String> e: prefixes.getPrefixes()) {
+ writer.writeNamespace(e.getValue(), e.getKey().toString());
+ }
+ LOG.debug("Instance identifier with Random prefix is now {}", str);
+ writer.writeCharacters(str);
+ }
+
+ /**
+ * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
+ *
+ * @param writer XML Stream writer
+ * @param data data node
+ * @param schema corresponding schema node, may be null
+ * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
+ */
+ public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
+ // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
+ // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
+
+ writer.writeStartDocument();
+ writeElement(writer, data, schema);
+ writer.writeEndDocument();
+ writer.flush();
+ }
+
+
+ /**
+ * Write an element into a XML stream writer. This includes the element start/end tags and
+ * the value of the element.
+ *
+ * @param writer XML Stream writer
+ * @param data data node
+ * @param schema Schema node
+ * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
+ */
+ public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
+ final QName qname = data.getNodeType();
+ final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
+ final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
+
+ if (isEmptyElement(data)) {
+ writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
+ return;
+ }
+
+ writer.writeStartElement(pfx, qname.getLocalName(), ns);
+ if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
+ for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
+ writer.writeAttribute(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(), attribute.getValue());
+ }
+ }
+
+ if (data instanceof SimpleNode<?>) {
+ LOG.debug("writeElement : node is of type SimpleNode");
+ // Simple node
+ if (schema instanceof LeafListSchemaNode) {
+ writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
+ } else if (schema instanceof LeafSchemaNode) {
+ writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
+ } else {
+ Object value = data.getValue();
+ if (value != null) {
+ writer.writeCharacters(String.valueOf(value));
+ }
+ }
+ } else {
+ LOG.debug("writeElement : node is of type CompositeNode");
+ // CompositeNode
+ for (Node<?> child : ((CompositeNode) data).getValue()) {
+ DataSchemaNode childSchema = null;
+ if (schema instanceof DataNodeContainer) {
+ childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
+ if (childSchema == null) {
+ LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
+ }
+ }
+
+ writeElement(writer, child, childSchema);
+ }
+ }
+
+ writer.writeEndElement();
+ }
+
+ /**
+ * Write a value into a XML stream writer. This method assumes the start and end of element is
+ * emitted by the caller.
+ *
+ * @param writer XML Stream writer
+ * @param type type definitions
+ * @param value object value
+ * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
+ */
+ public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
+ if (value == null) {
+ LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
+ return;
+ }
+
+ final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
+ if (baseType instanceof IdentityrefTypeDefinition) {
+ write(writer, (IdentityrefTypeDefinition) baseType, value);
+ } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
+ write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
+ } else {
+ final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
+ String text;
+ if (codec != null) {
+ try {
+ text = codec.serialize(value);
+ } catch (ClassCastException e) {
+ LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
+ text = String.valueOf(value);
+ }
+ } else {
+ LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
+ text = String.valueOf(value);
+ }
+ writer.writeCharacters(text);
+ }
+ }
+
+ private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
+ if (value instanceof QName) {
+ final QName qname = (QName) value;
+ final String prefix;
+ if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
+ prefix = qname.getPrefix();
+ } else {
+ prefix = "x";
+ }
+
+ writer.writeNamespace(prefix, qname.getNamespace().toString());
+ writer.writeCharacters(prefix + ':' + qname.getLocalName());
+ } else {
+ LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
+ writer.writeCharacters(String.valueOf(value));
+ }
+ }
+
+ private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
+ if (value instanceof YangInstanceIdentifier) {
+ LOG.debug("Writing InstanceIdentifier object {}", value);
+ write(writer, (YangInstanceIdentifier)value);
+ } else {
+ LOG.debug("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
+ writer.writeCharacters(String.valueOf(value));
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.remote.rpc.utils;
+
+import com.google.common.base.Optional;
+import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
+import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+import javax.activation.UnsupportedDataTypeException;
+import javax.annotation.Nonnull;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Common XML-related utility methods, which are not specific to a particular
+ * JAXP API.
+ */
+public class XmlUtils {
+
+ public static final XmlCodecProvider DEFAULT_XML_CODEC_PROVIDER = new XmlCodecProvider() {
+ @Override
+ public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
+ return TypeDefinitionAwareCodec.from(baseType);
+ }
+ };
+
+ private XmlUtils() {
+ }
+
+ private static final String BLANK = "";
+ private static final Logger LOG = LoggerFactory.getLogger(XmlUtils.class);
+
+ /**
+ * Converts the composite node to xml using rpc input schema node
+ * @param cNode
+ * @param schemaContext
+ * @return xml String
+ */
+ public static String inputCompositeNodeToXml(CompositeNode cNode, SchemaContext schemaContext){
+ LOG.debug("Converting input composite node to xml {}", cNode);
+ if (cNode == null) return BLANK;
+
+ if(schemaContext == null) return BLANK;
+
+ Document domTree = null;
+ try {
+ Set<RpcDefinition> rpcs = schemaContext.getOperations();
+ for(RpcDefinition rpc : rpcs) {
+ if(rpc.getQName().equals(cNode.getNodeType())){
+ LOG.debug("Found the rpc definition from schema context matching with input composite node {}", rpc.getQName());
+
+ CompositeNode inputContainer = cNode.getFirstCompositeByName(QName.create(cNode.getNodeType(), "input"));
+ domTree = XmlDocumentUtils.toDocument(inputContainer, rpc.getInput(), XmlDocumentUtils.defaultValueCodecProvider());
+
+ LOG.debug("input composite node to document conversion complete, document is {}", domTree);
+ break;
+ }
+ }
+
+ } catch (UnsupportedDataTypeException e) {
+ LOG.error("Error during translation of CompositeNode to Document", e);
+ }
+ return domTransformer(domTree);
+ }
+
+ /**
+ * Converts the composite node to xml String using rpc output schema node
+ * @param cNode
+ * @param schemaContext
+ * @return xml string
+ */
+ public static String outputCompositeNodeToXml(CompositeNode cNode, SchemaContext schemaContext){
+ LOG.debug("Converting output composite node to xml {}", cNode);
+ if (cNode == null) return BLANK;
+
+ if(schemaContext == null) return BLANK;
+
+ Document domTree = null;
+ try {
+ Set<RpcDefinition> rpcs = schemaContext.getOperations();
+ for(RpcDefinition rpc : rpcs) {
+ if(rpc.getQName().equals(cNode.getNodeType())){
+ LOG.debug("Found the rpc definition from schema context matching with output composite node {}", rpc.getQName());
+
+ CompositeNode outputContainer = cNode.getFirstCompositeByName(QName.create(cNode.getNodeType(), "output"));
+ domTree = XmlDocumentUtils.toDocument(outputContainer, rpc.getOutput(), XmlDocumentUtils.defaultValueCodecProvider());
+
+ LOG.debug("output composite node to document conversion complete, document is {}", domTree);
+ break;
+ }
+ }
+
+ } catch (UnsupportedDataTypeException e) {
+ LOG.error("Error during translation of CompositeNode to Document", e);
+ }
+ return domTransformer(domTree);
+ }
+
+ private static String domTransformer(Document domTree) {
+ StringWriter writer = new StringWriter();
+ try {
+ TransformerFactory tf = TransformerFactory.newInstance();
+ Transformer transformer = tf.newTransformer();
+ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ transformer.transform(new DOMSource(domTree), new StreamResult(writer));
+ } catch (TransformerException e) {
+
+ LOG.error("Error during translation of Document to OutputStream", e);
+ }
+ LOG.debug("Document to string conversion complete, xml string is {} ", writer.toString());
+
+ return writer.toString();
+ }
+
+ public static CompositeNode xmlToCompositeNode(String xml){
+ if (xml==null || xml.length()==0) return null;
+
+ Node<?> dataTree;
+ try {
+ dataTree = XmlTreeBuilder.buildDataTree(new ByteArrayInputStream(xml.getBytes()));
+ } catch (XMLStreamException e) {
+ LOG.error("Error during building data tree from XML", e);
+ return null;
+ }
+ if (dataTree == null) {
+ LOG.error("data tree is null");
+ return null;
+ }
+ if (dataTree instanceof SimpleNode) {
+ LOG.error("RPC XML was resolved as SimpleNode");
+ return null;
+ }
+ return (CompositeNode) dataTree;
+ }
+
+ /**
+ * Converts the xml to composite node using rpc input schema node
+ * @param rpc
+ * @param xml
+ * @param schemaContext
+ * @return CompositeNode object based on the input, if any of the input parameter is null, a null object is returned
+ */
+ public static CompositeNode inputXmlToCompositeNode(QName rpc, String xml, SchemaContext schemaContext){
+ LOG.debug("Converting input xml to composite node {}", xml);
+ if (xml==null || xml.length()==0) return null;
+
+ if(rpc == null) return null;
+
+ if(schemaContext == null) return null;
+
+ CompositeNode compositeNode = null;
+ try {
+
+ Document doc = XmlUtil.readXmlToDocument(xml);
+ Set<RpcDefinition> rpcs = schemaContext.getOperations();
+ for(RpcDefinition rpcDef : rpcs) {
+ if(rpcDef.getQName().equals(rpc)){
+ LOG.debug("found the rpc definition from schema context matching rpc {}", rpc);
+
+ if(rpcDef.getInput() == null) {
+ LOG.warn("found rpc definition's input is null");
+ return null;
+ }
+
+ QName input = rpcDef.getInput().getQName();
+ NodeList nodeList = doc.getElementsByTagNameNS(input.getNamespace().toString(), "input");
+ if(nodeList == null || nodeList.getLength() < 1) {
+ LOG.warn("xml does not have input entry. {}", xml);
+ return null;
+ }
+ Element xmlData = (Element)nodeList.item(0);
+
+ List<Node<?>> dataNodes = XmlDocumentUtils.toDomNodes(xmlData,
+ Optional.of(rpcDef.getInput().getChildNodes()), schemaContext);
+
+ LOG.debug("Converted xml input to list of nodes {}", dataNodes);
+
+ final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder();
+ it.setQName(input);
+ it.add(ImmutableCompositeNode.create(input, dataNodes));
+ compositeNode = it.toInstance();
+ break;
+ }
+ }
+ } catch (SAXException e) {
+ LOG.error("Error during building data tree from XML", e);
+ } catch (IOException e) {
+ LOG.error("Error during building data tree from XML", e);
+ }
+
+ LOG.debug("Xml to composite node conversion complete {} ", compositeNode);
+ return compositeNode;
+ }
+
+ public static TypeDefinition<?> resolveBaseTypeFrom(final @Nonnull TypeDefinition<?> type) {
+ TypeDefinition<?> superType = type;
+ while (superType.getBaseType() != null) {
+ superType = superType.getBaseType();
+ }
+ return superType;
+ }
+
+ /**
+ * This code is picked from yangtools and modified to add type of instance identifier
+ * output of instance identifier something like below for a flow ref composite node of type instance identifier,
+ * which has path arguments with predicates, whose value is of type java.lang.short
+ * <flow-ref xmlns:bgkj="urn:opendaylight:flow:inventory" xmlns:jdlk="urn:opendaylight:inventory">
+ * /jdlk:nodes/jdlk:node[jdlk:id='openflow:205558455098190@java.lang.String']
+ * /bgkj:table[bgkj:id='3@java.lang.Short']
+ * /bgkj:flow[bgkj:id='156@java.lang.String']
+ * </flow-ref>
+ *
+ */
+
+ public static String encodeIdentifier(final RandomPrefix prefixes, final YangInstanceIdentifier id) {
+ StringBuilder textContent = new StringBuilder();
+ for (PathArgument pathArgument : id.getPathArguments()) {
+ textContent.append('/');
+ textContent.append(prefixes.encodeQName(pathArgument.getNodeType()));
+ if (pathArgument instanceof NodeIdentifierWithPredicates) {
+ Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
+
+ for (QName keyValue : predicates.keySet()) {
+ Object value = predicates.get(keyValue);
+ String type = value.getClass().getName();
+ String predicateValue = String.valueOf(value);
+ textContent.append('[');
+ textContent.append(prefixes.encodeQName(keyValue));
+ textContent.append("='");
+ textContent.append(predicateValue);
+ textContent.append("@");
+ textContent.append(type);
+ textContent.append("']");
+ }
+ } else if (pathArgument instanceof NodeWithValue) {
+ textContent.append("[.='");
+ textContent.append(((NodeWithValue) pathArgument).getValue());
+ textContent.append("']");
+ }
+ }
+
+ return textContent.toString();
+ }
+}
remote {
log-remote-lifecycle-events = off
netty.tcp {
- hostname = "192.168.141.142"
+ hostname = "192.168.141.141"
port = 2551
}
}
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
Broker.ProviderSession brokerSession = Mockito.mock(Broker.ProviderSession.class);
SchemaContext schemaContext = mock(SchemaContext.class);
ActorRef rpcBroker = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext));
- QName rpc = new QName(new URI("actor1"), "actor1");
- InvokeRpc invokeMsg = new InvokeRpc(rpc, null);
+ QName rpc = new QName(new URI("noactor1"), "noactor1");
+ CompositeNode input = new ImmutableCompositeNode(QName.create("ns", "2013-12-09", "no child"), new ArrayList<Node<?>>(), ModifyAction.REPLACE);
+ InvokeRpc invokeMsg = new InvokeRpc(rpc, input);
rpcBroker.tell(invokeMsg, getRef());
Boolean getMsg = new ExpectMsg<Boolean>("ErrorResponse") {
protected Boolean match(Object in) {
if (in instanceof ErrorResponse) {
ErrorResponse reply = (ErrorResponse)in;
- return "No remote actor found for rpc execution.".equals(reply.getException().getMessage());
+ return reply.getException().getMessage().contains("No remote actor found for rpc execution of :");
} else {
throw noMatch();
}
SchemaContext schemaContext = mock(SchemaContext.class);
ActorRef rpcBroker = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext));
QName rpc = new QName(new URI("actor1"), "actor1");
- InvokeRoutedRpc invokeMsg = new InvokeRoutedRpc(rpc, null);
+ CompositeNode input = new ImmutableCompositeNode(QName.create("ns", "2013-12-09", "child1"), new ArrayList<Node<?>>(), ModifyAction.REPLACE);
+ InvokeRoutedRpc invokeMsg = new InvokeRoutedRpc(rpc, YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(rpc)), input);
rpcBroker.tell(invokeMsg, getRef());
Boolean getMsg = new ExpectMsg<Boolean>("ErrorResponse") {
ActorRef rpcBrokerRemote = system.actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), "actor2");
// Add Routed RPC in table
QName rpc = new QName(new URI("actor2"), "actor2");
- RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, rpc, null);
+ YangInstanceIdentifier identifier = YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(rpc));
+ RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, rpc, identifier);
final String route = rpcBrokerRemote.path().toString();
Set<RpcRouter.RouteIdentifier<?, ?, ?>> routeIds = new HashSet<>();
routeIds.add(routeId);
RpcResult<CompositeNode> result = Rpcs.getRpcResult(true, invokeRpcResult, errors);
Future<RpcResult<CompositeNode>> rpcResult = Futures.immediateFuture(result);
when(brokerSession.rpc(rpc, input)).thenReturn(rpcResult);
- InvokeRoutedRpc invokeMsg = new InvokeRoutedRpc(rpc, input);
+ InvokeRoutedRpc invokeMsg = new InvokeRoutedRpc(rpc, identifier, input);
rpcBroker.tell(invokeMsg, getRef());
//verify response msg
@Test
public void addGlobalRouteNullRouteTest() {
try {
- RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, null, null);
+ QName type = new QName(new URI("actor1"), "actor1");
+ RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
routingTable.addGlobalRoute(routeId, null);
Assert.fail("Null pointer exception was not thrown.");
@Test
public void addRoutedRpcNullRouteTest() {
try {
- RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, null, null);
+ QName type = new QName(new URI("actor1"), "actor1");
+ RouteIdentifierImpl routeId = new RouteIdentifierImpl(null, type, null);
routingTable.addRoutedRpc(routeId, null);
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.remote.rpc.utils;
+
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.common.io.ByteSource;
+import junit.framework.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+
+public class XmlUtilsTest {
+
+ private static final DocumentBuilderFactory BUILDERFACTORY;
+
+ static {
+ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ factory.setCoalescing(true);
+ factory.setIgnoringElementContentWhitespace(true);
+ factory.setIgnoringComments(true);
+ BUILDERFACTORY = factory;
+ }
+
+ private SchemaContext schema;
+ private RpcDefinition testRpc;
+
+ public static final String XML_CONTENT = "<add-flow xmlns=\"urn:opendaylight:controller:rpc:test\"><input xmlns=\"urn:opendaylight:controller:rpc:test\">" +
+ "<id>flowid</id>" +
+ "<flow xmlns:ltha=\"urn:opendaylight:controller:rpc:test\">/ltha:node/ltha:node1[ltha:id='3@java.lang.Short']</flow>" +
+ "</input></add-flow>";
+
+ @Before
+ public void setUp() throws Exception {
+ final ByteSource byteSource = new ByteSource() {
+ @Override
+ public InputStream openStream() throws IOException {
+ return XmlUtilsTest.this.getClass().getResourceAsStream("rpcTest.yang");
+ }
+ };
+ schema = new YangParserImpl().parseSources(Lists.newArrayList(byteSource));
+ final Module rpcTestModule = schema.getModules().iterator().next();
+ testRpc = rpcTestModule.getRpcs().iterator().next();
+ }
+
+ @Test
+ public void testNullInputXmlToComposite() {
+ CompositeNode node = XmlUtils.inputXmlToCompositeNode(testRpc.getQName(), null, schema);
+ Assert.assertNull(node);
+ }
+
+ @Test
+ public void testNullRpcXmlToComposite() {
+ CompositeNode node = XmlUtils.inputXmlToCompositeNode(null, XML_CONTENT, schema);
+ Assert.assertNull(node);
+ }
+
+ @Test
+ public void testInputXmlToCompositeNode() {
+ CompositeNode node = XmlUtils.inputXmlToCompositeNode(testRpc.getQName(), XML_CONTENT, schema);
+ ImmutableList<SimpleNode> input = (ImmutableList)node.getValue().get(0).getValue();
+ SimpleNode firstNode = input.get(0);
+
+ Assert.assertEquals("id", firstNode.getNodeType().getLocalName());
+ Assert.assertEquals("flowid", firstNode.getValue());
+
+ SimpleNode secondNode = input.get(1);
+ Assert.assertEquals("flow", secondNode.getNodeType().getLocalName());
+
+ YangInstanceIdentifier instance = (YangInstanceIdentifier) secondNode.getValue();
+ Iterable<YangInstanceIdentifier.PathArgument> iterable = instance.getPathArguments();
+ Iterator it = iterable.iterator();
+ YangInstanceIdentifier.NodeIdentifier firstPath = (YangInstanceIdentifier.NodeIdentifier) it.next();
+ Assert.assertEquals("node", firstPath.getNodeType().getLocalName());
+ YangInstanceIdentifier.NodeIdentifierWithPredicates secondPath = (YangInstanceIdentifier.NodeIdentifierWithPredicates)it.next();
+ Short value = (Short)secondPath.getKeyValues().values().iterator().next();
+ Short expected = 3;
+ Assert.assertEquals(expected, value);
+ }
+
+ @Test
+ public void testInputCompositeNodeToXML() {
+ CompositeNode input = XmlUtils.inputXmlToCompositeNode(testRpc.getQName(), XML_CONTENT, schema);
+ List<Node<?>> childNodes = new ArrayList();
+ childNodes.add(input);
+ QName rpcQName = schema.getOperations().iterator().next().getQName();
+ CompositeNode node = new ImmutableCompositeNode(rpcQName, input.getValue(), ModifyAction.REPLACE);
+ String xml = XmlUtils.inputCompositeNodeToXml(node, schema);
+ Assert.assertNotNull(xml);
+ Assert.assertTrue(xml.contains("3@java.lang.Short"));
+ }
+
+ @Test
+ public void testNullCompositeNodeToXml(){
+ String xml = XmlUtils.inputCompositeNodeToXml(null, schema);
+ Assert.assertTrue(xml.isEmpty());
+ }
+
+ @Test
+ public void testNullSchemaCompositeNodeToXml(){
+ String xml = XmlUtils.inputCompositeNodeToXml(new ImmutableCompositeNode(QName.create("ns", "2013-12-09", "child1"), new ArrayList<Node<?>>(), ModifyAction.REPLACE), null);
+ Assert.assertTrue(xml.isEmpty());
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+module rpc-test {
+ yang-version 1;
+ namespace "urn:opendaylight:controller:rpc:test";
+ prefix "rpct";
+
+ revision 2014-07-29 {
+ description "rpc test";
+ }
+
+ typedef flow-ref {
+ type instance-identifier;
+ }
+
+ rpc add-flow {
+ input {
+ leaf id {
+ type string;
+ }
+
+ leaf flow {
+ type flow-ref;
+ }
+ }
+ }
+}
\ No newline at end of file
import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
public class RestconfProviderImpl implements Provider, AutoCloseable, RestConnector {
public final static String NOT_INITALIZED_MSG = "Restconf is not initialized yet. Please try again later";
- private ListenerRegistration<SchemaServiceListener> listenerRegistration;
+ private ListenerRegistration<SchemaContextListener> listenerRegistration;
private PortNumber port;
public void setWebsocketPort(PortNumber port) {
this.port = port;
BrokerFacade.getInstance().setDataService(dataService);
SchemaService schemaService = session.getService(SchemaService.class);
- listenerRegistration = schemaService.registerSchemaServiceListener(ControllerContext.getInstance());
+ listenerRegistration = schemaService.registerSchemaContextListener(ControllerContext.getInstance());
ControllerContext.getInstance().setSchemas(schemaService.getGlobalContext());
ControllerContext.getInstance().setMountService(session.getService(MountService.class));
DataSchemaNode ret = container.getDataChildByName(name);
if (ret == null) {
for (final DataSchemaNode node : container.getChildNodes()) {
- if ((node instanceof ChoiceCaseNode)) {
- final ChoiceCaseNode caseNode = ((ChoiceCaseNode) node);
- DataSchemaNode childByQName = ControllerContext.childByQName(caseNode, name);
+ if ((node instanceof ChoiceNode)) {
+ final ChoiceNode choiceNode = ((ChoiceNode) node);
+ DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
if (childByQName != null) {
return childByQName;
}
result = result.substring(1);
}
if (result.endsWith("/")) {
- result = result.substring(0, result.length());
+ result = result.substring(0, result.length()-1);
}
return result;
}
<module>toaster</module>
<module>toaster-consumer</module>
<module>toaster-provider</module>
+ <module>toaster-config</module>
<module>l2switch</module>
</modules>
<scm>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>sal-samples</artifactId>
+ <version>1.1-SNAPSHOT</version>
+ </parent>
+ <artifactId>toaster-config</artifactId>
+ <description>Configuration files for toaster</description>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-artifacts</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>${project.build.directory}/classes/initial/03-toaster-sample.xml</file>
+ <type>xml</type>
+ <classifier>config</classifier>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
<type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-async-data-broker</type>
<name>binding-data-broker</name>
</data-broker>
-
+
<notification-service>
<type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
binding:binding-notification-service
</notification-service>
</module>
</modules>
-
+
<services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
<service>
<type xmlns:kitchen="urn:opendaylight:params:xml:ns:yang:controller:config:kitchen-service:impl">
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-subsystem</artifactId>
+ <version>0.2.5-SNAPSHOT</version>
+ </parent>
+ <artifactId>netconf-config</artifactId>
+ <description>Configuration files for netconf</description>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-artifacts</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>${project.build.directory}/classes/initial/01-netconf.xml</file>
+ <type>xml</type>
+ <classifier>config</classifier>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-subsystem</artifactId>
+ <version>0.2.5-SNAPSHOT</version>
+ </parent>
+ <artifactId>netconf-connector-config</artifactId>
+ <description>Configuration files for netconf-connector</description>
+ <packaging>jar</packaging>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-artifacts</id>
+ <goals>
+ <goal>attach-artifact</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <artifacts>
+ <artifact>
+ <file>${project.build.directory}/classes/initial/99-netconf-connector.xml</file>
+ <type>xml</type>
+ <classifier>config</classifier>
+ </artifact>
+ </artifacts>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
<modules>
<module>netconf-api</module>
<module>netconf-cli</module>
+ <module>netconf-config</module>
<module>netconf-impl</module>
<module>config-netconf-connector</module>
<module>netconf-util</module>
<module>netconf-monitoring</module>
<module>ietf-netconf-monitoring</module>
<module>ietf-netconf-monitoring-extension</module>
+ <module>netconf-connector-config</module>
</modules>
<dependencies>
*/
List<NeutronPort> myPorts;
- boolean gatewayIPAssigned;
+ Boolean gatewayIPAssigned;
public NeutronSubnet() {
myPorts = new ArrayList<NeutronPort>();
try {
SubnetUtils util = new SubnetUtils(cidr);
SubnetInfo info = util.getInfo();
- if (gatewayIP == null) {
+ if (gatewayIP == null || ("").equals(gatewayIP)) {
gatewayIP = info.getLowAddress();
}
if (allocationPools.size() < 1) {
gatewayIPAssigned = false;
}
+ public Boolean getGatewayIPAllocated() {
+ return gatewayIPAssigned;
+ }
+
@Override
public String toString() {
return "NeutronSubnet [subnetUUID=" + subnetUUID + ", networkUUID=" + networkUUID + ", name=" + name
javax.ws.rs.core,
javax.xml.bind,
javax.xml.bind.annotation,
- org.objectweb.asm,
org.opendaylight.controller.sal.utils,
org.opendaylight.controller.sal.core,
org.opendaylight.controller.sal.authorization,
if (instances != null) {
for (Object instance : instances) {
INeutronRouterAware service = (INeutronRouterAware) instance;
- service.canAttachInterface(target, input);
+ int status = service.canAttachInterface(target, input);
+ if (status < 200 || status > 299)
+ return Response.status(status).build();
}
}
if (instances != null) {
for (Object instance : instances) {
INeutronRouterAware service = (INeutronRouterAware) instance;
- service.canDetachInterface(target, input);
+ int status = service.canDetachInterface(target, input);
+ if (status < 200 || status > 299)
+ return Response.status(status).build();
}
}