Fix logging mismatches
[bgpcep.git] / pcep / pcc-mock / src / main / java / org / opendaylight / protocol / pcep / pcc / mock / Main.java
old mode 100644 (file)
new mode 100755 (executable)
index fec2ac8..3f1ce82
@@ -10,30 +10,18 @@ package org.opendaylight.protocol.pcep.pcc.mock;
 
 import ch.qos.logback.classic.Level;
 import ch.qos.logback.classic.LoggerContext;
-import com.google.common.base.Charsets;
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import com.google.common.net.InetAddresses;
-import io.netty.util.concurrent.GlobalEventExecutor;
+import java.math.BigInteger;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.ExecutionException;
-import org.opendaylight.protocol.framework.ReconnectImmediatelyStrategy;
-import org.opendaylight.protocol.framework.SessionListenerFactory;
-import org.opendaylight.protocol.framework.SessionNegotiatorFactory;
-import org.opendaylight.protocol.pcep.PCEPSessionListener;
-import org.opendaylight.protocol.pcep.ietf.stateful07.StatefulActivator;
-import org.opendaylight.protocol.pcep.impl.DefaultPCEPSessionNegotiatorFactory;
-import org.opendaylight.protocol.pcep.impl.PCEPSessionImpl;
-import org.opendaylight.protocol.pcep.spi.pojo.ServiceLoaderPCEPExtensionProviderContext;
-import org.opendaylight.tcpmd5.api.KeyMapping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder;
+import org.opendaylight.protocol.pcep.PCEPCapability;
+import org.opendaylight.protocol.pcep.ietf.stateful07.PCEPStatefulCapability;
+import org.opendaylight.protocol.util.InetSocketAddressUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -41,16 +29,28 @@ public final class Main {
 
     private static final Logger LOG = LoggerFactory.getLogger(Main.class);
 
-    private static final int DEFAULT_PORT = 4189;
+    private static final int DEFAULT_REMOTE_PORT = 4189;
+    private static final int DEFAULT_LOCAL_PORT = 0;
     private static final short DEFAULT_KEEP_ALIVE = 30;
     private static final short DEFAULT_DEAD_TIMER = 120;
-    private static final int RECONNECT_STRATEGY_TIMEOUT = 2000;
+    private static final InetAddress LOCALHOST = InetAddresses.forString("127.0.0.1");
+    private static boolean triggeredInitSync = Boolean.FALSE;
+    private static boolean includeDbv = Boolean.FALSE;
+    private static boolean incrementalSync = Boolean.FALSE;
+    private static boolean triggeredResync = Boolean.FALSE;
+    private static BigInteger syncOptDBVersion;
+    private static int reconnectAfterXSeconds;
+    private static int disonnectAfterXSeconds;
 
-    private Main() { }
 
-    public static void main(final String[] args) throws InterruptedException, ExecutionException, UnknownHostException {
-        InetAddress localAddress = InetAddress.getByName("127.0.0.1");
-        List<InetAddress> remoteAddress = Lists.newArrayList(InetAddress.getByName("127.0.0.1"));
+    private Main() {
+        throw new UnsupportedOperationException();
+    }
+
+    public static void main(final String[] args) throws InterruptedException, ExecutionException {
+        InetSocketAddress localAddress = new InetSocketAddress(LOCALHOST, DEFAULT_LOCAL_PORT);
+        List<InetSocketAddress> remoteAddress = Collections
+                .singletonList(new InetSocketAddress(LOCALHOST, DEFAULT_REMOTE_PORT));
         int pccCount = 1;
         int lsps = 1;
         boolean pcError = false;
@@ -58,99 +58,111 @@ public final class Main {
         short ka = DEFAULT_KEEP_ALIVE;
         short dt = DEFAULT_DEAD_TIMER;
         String password = null;
+        long reconnectTime = -1;
+        int redelegationTimeout = 0;
+        int stateTimeout = -1;
 
         getRootLogger(lc).setLevel(ch.qos.logback.classic.Level.INFO);
         int argIdx = 0;
         while (argIdx < args.length) {
-            if (args[argIdx].equals("--local-address")) {
-                localAddress = InetAddress.getByName(args[++argIdx]);
-            } else if (args[argIdx].equals("--remote-address")) {
-                remoteAddress = parseAddresses(args[++argIdx]);
-            } else if (args[argIdx].equals("--pcc")) {
-                pccCount = Integer.valueOf(args[++argIdx]);
-            } else if (args[argIdx].equals("--lsp")) {
-                lsps = Integer.valueOf(args[++argIdx]);
-            } else if (args[argIdx].equals("--pcerr")) {
-                pcError = true;
-            } else if (args[argIdx].equals("--log-level")) {
-                getRootLogger(lc).setLevel(Level.toLevel(args[++argIdx], ch.qos.logback.classic.Level.INFO));
-            } else if (args[argIdx].equals("--keepalive") || args[argIdx].equals("-ka")) {
-                ka = Short.valueOf(args[++argIdx]);
-            } else if (args[argIdx].equals("--deadtimer") || args[argIdx].equals("-d")) {
-                dt = Short.valueOf(args[++argIdx]);
-            } else if (args[argIdx].equals("--password")) {
-                password = args[++argIdx];
-            } else {
-                LOG.warn("WARNING: Unrecognized argument: {}", args[argIdx]);
+            switch (args[argIdx]) {
+                case "--local-address":
+                    localAddress = InetSocketAddressUtil.getInetSocketAddress(args[++argIdx], DEFAULT_LOCAL_PORT);
+                    break;
+                case "--remote-address":
+                    remoteAddress = InetSocketAddressUtil.parseAddresses(args[++argIdx], DEFAULT_REMOTE_PORT);
+                    break;
+                case "--pcc":
+                    pccCount = Integer.parseInt(args[++argIdx]);
+                    break;
+                case "--lsp":
+                    lsps = Integer.parseInt(args[++argIdx]);
+                    break;
+                case "--pcerr":
+                    pcError = true;
+                    break;
+                case "--log-level":
+                    getRootLogger(lc).setLevel(Level.toLevel(args[++argIdx], Level.INFO));
+                    break;
+                case "--keepalive":
+                case "-ka":
+                    ka = Short.valueOf(args[++argIdx]);
+                    break;
+                case "--deadtimer":
+                case "-d":
+                    dt = Short.valueOf(args[++argIdx]);
+                    break;
+                case "--password":
+                    password = args[++argIdx];
+                    break;
+                case "--reconnect":
+                    reconnectTime = Integer.parseInt(args[++argIdx]);
+                    break;
+                case "--redelegation-timeout":
+                    redelegationTimeout = Integer.parseInt(args[++argIdx]);
+                    break;
+                case "--state-timeout":
+                    stateTimeout = Integer.parseInt(args[++argIdx]);
+                    break;
+                case "--state-sync-avoidance":
+                    //"--state-sync-avoidance 10, 5, 10
+                    includeDbv = Boolean.TRUE;
+                    final Long dbVersionAfterReconnect = Long.valueOf(args[++argIdx]);
+                    disonnectAfterXSeconds = Integer.parseInt(args[++argIdx]);
+                    reconnectAfterXSeconds = Integer.parseInt(args[++argIdx]);
+                    syncOptDBVersion = BigInteger.valueOf(dbVersionAfterReconnect);
+                    break;
+                case "--incremental-sync-procedure":
+                    //TODO Check that DBv > Lsp always ??
+                    includeDbv = Boolean.TRUE;
+                    incrementalSync = Boolean.TRUE;
+                    //Version of database to be used after restart
+                    final Long initialDbVersionAfterReconnect = Long.valueOf(args[++argIdx]);
+                    disonnectAfterXSeconds = Integer.parseInt(args[++argIdx]);
+                    reconnectAfterXSeconds = Integer.parseInt(args[++argIdx]);
+                    syncOptDBVersion = BigInteger.valueOf(initialDbVersionAfterReconnect);
+                    break;
+                case "--triggered-initial-sync":
+                    triggeredInitSync = Boolean.TRUE;
+                    break;
+                case "--triggered-re-sync":
+                    triggeredResync = Boolean.TRUE;
+                    break;
+                default:
+                    LOG.warn("WARNING: Unrecognized argument: {}", args[argIdx]);
+                    break;
             }
             argIdx++;
         }
-        createPCCs(lsps, pcError, pccCount, localAddress, remoteAddress, ka, dt, password);
-    }
 
-    public static void createPCCs(final int lspsPerPcc, final boolean pcerr, final int pccCount,
-            final InetAddress localAddress, final List<InetAddress> remoteAddress, final short keepalive, final short deadtimer,
-            final String password) throws InterruptedException, ExecutionException {
-        final StatefulActivator activator07 = new StatefulActivator();
-        activator07.start(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance());
-        InetAddress currentAddress = localAddress;
-        final PCCDispatcher pccDispatcher = new PCCDispatcher(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance().getMessageHandlerRegistry(),
-                getSessionNegotiatorFactory(keepalive, deadtimer));
-        for (int i = 0; i < pccCount; i++) {
-            createPCC(lspsPerPcc, pcerr, currentAddress, remoteAddress, keepalive, deadtimer, pccDispatcher, password);
-            currentAddress = InetAddresses.increment(currentAddress);
+        if (incrementalSync) {
+            Preconditions.checkArgument(syncOptDBVersion.intValue() > lsps,
+                    "Synchronization Database Version which will be used after "
+                            + "reconnectes requires to be higher than lsps");
         }
-    }
 
-    private static void createPCC(final int lspsPerPcc, final boolean pcerr, final InetAddress localAddress,
-            final List<InetAddress> remoteAddress, final short keepalive, final short deadtimer, final PCCDispatcher pccDispatcher,
-            final String password) throws InterruptedException, ExecutionException {
-        final SessionNegotiatorFactory<Message, PCEPSessionImpl, PCEPSessionListener> snf = getSessionNegotiatorFactory(keepalive, deadtimer);
-        for (final InetAddress pceAddress : remoteAddress) {
-            pccDispatcher.createClient(new InetSocketAddress(localAddress, 0), new InetSocketAddress(pceAddress, DEFAULT_PORT), new ReconnectImmediatelyStrategy(GlobalEventExecutor.INSTANCE, RECONNECT_STRATEGY_TIMEOUT), new SessionListenerFactory<PCEPSessionListener>() {
-                @Override
-                public PCEPSessionListener getSessionListener() {
-                    return new SimpleSessionListener(lspsPerPcc, pcerr, localAddress);
-                }
-            }, snf, getKeyMapping(pceAddress, password));
+        final Optional<BigInteger> dBVersion = Optional.fromNullable(syncOptDBVersion);
+        final PCCsBuilder pccs = new PCCsBuilder(lsps, pcError, pccCount, localAddress, remoteAddress, ka, dt,
+                password, reconnectTime, redelegationTimeout,
+            stateTimeout, getCapabilities());
+        final TimerHandler timerHandler = new TimerHandler(pccs, dBVersion, disonnectAfterXSeconds,
+                reconnectAfterXSeconds);
+        pccs.createPCCs(BigInteger.valueOf(lsps), Optional.fromNullable(timerHandler));
+        if (!triggeredInitSync) {
+            timerHandler.createDisconnectTask();
         }
     }
 
-    private static SessionNegotiatorFactory<Message, PCEPSessionImpl, PCEPSessionListener> getSessionNegotiatorFactory(final short keepalive,
-            final short deadtimer) {
-        return new DefaultPCEPSessionNegotiatorFactory(
-                new OpenBuilder().setKeepalive(keepalive).setDeadTimer(deadtimer).setSessionId((short) 0).build(), 0);
+    private static PCEPCapability getCapabilities() {
+        if (triggeredInitSync) {
+            Preconditions.checkArgument(includeDbv);
+        }
+        return new PCEPStatefulCapability(true, true, true, triggeredInitSync, triggeredResync,
+                incrementalSync, includeDbv);
     }
 
     private static ch.qos.logback.classic.Logger getRootLogger(final LoggerContext lc) {
-        return Iterables.find(lc.getLoggerList(), new Predicate<Logger>() {
-            @Override
-            public boolean apply(final Logger input) {
-                return (input != null) ? input.getName().equals(Logger.ROOT_LOGGER_NAME) : false;
-            }
-        });
+        return lc.getLoggerList().stream().filter(input -> (input != null) && input.getName()
+            .equals(Logger.ROOT_LOGGER_NAME)).findFirst().get();
     }
-
-    private static List<InetAddress> parseAddresses(final String address) {
-        return Lists.transform(Arrays.asList(address.split(",")), new Function<String, InetAddress>() {
-            @Override
-            public InetAddress apply(String input) {
-                try {
-                    return InetAddress.getByName(input);
-                } catch (UnknownHostException e) {
-                    throw new RuntimeException("Not an IP address: " + input, e);
-                }
-            }
-        });
-    }
-
-    private static KeyMapping getKeyMapping(final InetAddress inetAddress, final String password) {
-        if (password != null) {
-            final KeyMapping keyMapping = new KeyMapping();
-            keyMapping.put(inetAddress, password.getBytes(Charsets.US_ASCII));
-            return keyMapping;
-        }
-        return null;
-    }
-
 }