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 7cff740..3f1ce82
@@ -10,36 +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.net.HostAndPort;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import com.google.common.net.InetAddresses;
-import io.netty.util.HashedWheelTimer;
-import io.netty.util.Timer;
+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 java.util.concurrent.TimeUnit;
 import org.opendaylight.protocol.pcep.PCEPCapability;
-import org.opendaylight.protocol.pcep.PCEPSessionListener;
-import org.opendaylight.protocol.pcep.PCEPSessionListenerFactory;
-import org.opendaylight.protocol.pcep.PCEPSessionNegotiatorFactory;
-import org.opendaylight.protocol.pcep.ietf.initiated00.CrabbeInitiatedActivator;
 import org.opendaylight.protocol.pcep.ietf.stateful07.PCEPStatefulCapability;
-import org.opendaylight.protocol.pcep.ietf.stateful07.StatefulActivator;
-import org.opendaylight.protocol.pcep.impl.BasePCEPSessionProposalFactory;
-import org.opendaylight.protocol.pcep.impl.DefaultPCEPSessionNegotiatorFactory;
-import org.opendaylight.protocol.pcep.impl.PCEPSessionImpl;
-import org.opendaylight.protocol.pcep.pcc.mock.api.PccTunnelManager;
-import org.opendaylight.protocol.pcep.spi.PCEPExtensionProviderContext;
-import org.opendaylight.protocol.pcep.spi.pojo.ServiceLoaderPCEPExtensionProviderContext;
-import org.opendaylight.tcpmd5.api.KeyMapping;
+import org.opendaylight.protocol.util.InetSocketAddressUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -52,15 +34,23 @@ public final class Main {
     private static final short DEFAULT_KEEP_ALIVE = 30;
     private static final short DEFAULT_DEAD_TIMER = 120;
     private static final InetAddress LOCALHOST = InetAddresses.forString("127.0.0.1");
-    private static final PCEPCapability STATEFUL_CAPABILITY = new PCEPStatefulCapability(true, true, true,
-            false, false, false, false);
-    private static final List<PCEPCapability> CAPABILITIES = Lists.newArrayList(STATEFUL_CAPABILITY);
+    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 {
+    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 = Lists.newArrayList(new InetSocketAddress(LOCALHOST, DEFAULT_REMOTE_PORT));
+        List<InetSocketAddress> remoteAddress = Collections
+                .singletonList(new InetSocketAddress(LOCALHOST, DEFAULT_REMOTE_PORT));
         int pccCount = 1;
         int lsps = 1;
         boolean pcError = false;
@@ -71,117 +61,108 @@ public final class Main {
         long reconnectTime = -1;
         int redelegationTimeout = 0;
         int stateTimeout = -1;
-        final Timer timer = new HashedWheelTimer();
 
         getRootLogger(lc).setLevel(ch.qos.logback.classic.Level.INFO);
         int argIdx = 0;
         while (argIdx < args.length) {
-            if (args[argIdx].equals("--local-address")) {
-                localAddress = getInetSocketAddress(args[++argIdx], DEFAULT_LOCAL_PORT);
-            } else if (args[argIdx].equals("--remote-address")) {
-                remoteAddress = parseAddresses(args[++argIdx], DEFAULT_REMOTE_PORT);
-            } 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 if (args[argIdx].equals("--reconnect")) {
-                reconnectTime =  TimeUnit.SECONDS.toMillis(Integer.valueOf(args[++argIdx]).intValue());
-            } else if (args[argIdx].equals("--redelegation-timeout")) {
-                redelegationTimeout = Integer.valueOf(args[++argIdx]);
-            } else if (args[argIdx].equals("--state-timeout")) {
-                stateTimeout = Integer.valueOf(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, reconnectTime, redelegationTimeout, stateTimeout, timer);
-    }
 
-    public static void createPCCs(final int lspsPerPcc, final boolean pcerr, final int pccCount,
-            final InetSocketAddress localAddress, final List<InetSocketAddress> remoteAddress, final short keepalive, final short deadtimer,
-            final String password, final long reconnectTime, final int redelegationTimeout, final int stateTimeout, final Timer timer) throws InterruptedException, ExecutionException {
-        startActivators();
-        InetAddress currentAddress = localAddress.getAddress();
-        final PccDispatcherImpl pccDispatcher = new PccDispatcherImpl(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance().getMessageHandlerRegistry());
-        for (int i = 0; i < pccCount; i++) {
-            final PccTunnelManager tunnelManager = new PccTunnelManagerImpl(lspsPerPcc, currentAddress,
-                    redelegationTimeout, stateTimeout, timer);
-            createPCC(pcerr, new InetSocketAddress(currentAddress, localAddress.getPort()),
-                    remoteAddress, getSessionNegotiatorFactory(keepalive, deadtimer), pccDispatcher, password, reconnectTime, tunnelManager);
-            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 boolean pcerr, final InetSocketAddress localAddress,
-            final List<InetSocketAddress> remoteAddress, final PCEPSessionNegotiatorFactory<PCEPSessionImpl> snf, final PccDispatcherImpl pccDispatcher,
-            final String password, final long reconnectTime, final PccTunnelManager tunnelManager) throws InterruptedException, ExecutionException {
 
-        for (final InetSocketAddress pceAddress : remoteAddress) {
-            pccDispatcher.createClient(pceAddress, reconnectTime,
-                    new PCEPSessionListenerFactory() {
-                        @Override
-                        public PCEPSessionListener getSessionListener() {
-                            return new PccSessionListener(remoteAddress.indexOf(pceAddress), tunnelManager, pcerr);
-                        }
-                    }, snf, getKeyMapping(pceAddress.getAddress(), password), localAddress);
+        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 PCEPSessionNegotiatorFactory<PCEPSessionImpl> getSessionNegotiatorFactory(final short keepAlive, final short deadTimer) {
-        return new DefaultPCEPSessionNegotiatorFactory(new BasePCEPSessionProposalFactory(deadTimer, keepAlive, CAPABILITIES), 0);
-    }
-
-    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;
-            }
-        });
-    }
-
-    private static List<InetSocketAddress> parseAddresses(final String address, final int defaultPort) {
-        return Lists.transform(Arrays.asList(address.split(",")), new Function<String, InetSocketAddress>() {
-            @Override
-            public InetSocketAddress apply(final String input) {
-                return getInetSocketAddress(input, defaultPort);
-            }
-        });
-    }
-
-    private static InetSocketAddress getInetSocketAddress(final String hostPortString, final int defaultPort) {
-        final HostAndPort hostAndPort = HostAndPort.fromString(hostPortString).withDefaultPort(defaultPort);
-        return new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort());
-    }
-
-    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;
+    private static PCEPCapability getCapabilities() {
+        if (triggeredInitSync) {
+            Preconditions.checkArgument(includeDbv);
         }
-        return null;
+        return new PCEPStatefulCapability(true, true, true, triggeredInitSync, triggeredResync,
+                incrementalSync, includeDbv);
     }
 
-    private static void startActivators() {
-        final PCCActivator pccActivator = new PCCActivator();
-        final StatefulActivator stateful = new StatefulActivator();
-        final CrabbeInitiatedActivator activator = new CrabbeInitiatedActivator();
-        final PCEPExtensionProviderContext ctx = ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance();
-        pccActivator.start(ctx);
-        stateful.start(ctx);
-        activator.start(ctx);
+    private static ch.qos.logback.classic.Logger getRootLogger(final LoggerContext lc) {
+        return lc.getLoggerList().stream().filter(input -> (input != null) && input.getName()
+            .equals(Logger.ROOT_LOGGER_NAME)).findFirst().get();
     }
-
 }