Example #1
0
        private void Run(int port)
        {
            var protocol = new RingMasterCommunicationProtocol();

            this.CreateBackend();

            using (var cancel = new CancellationTokenSource())
            {
                this.ringMasterServer = new RingMasterServer(protocol, null, cancel.Token);

                var transportConfig = new SecureTransport.Configuration
                {
                    UseSecureConnection          = false,
                    IsClientCertificateRequired  = false,
                    CommunicationProtocolVersion = RingMasterCommunicationProtocol.MaximumSupportedVersion,
                };

                using (var serverTransport = new SecureTransport(transportConfig))
                {
                    this.ringMasterServer.RegisterTransport(serverTransport);
                    this.ringMasterServer.OnInitSession = initRequest =>
                    {
                        return(new CoreRequestHandler(this.backend, initRequest));
                    };

                    serverTransport.StartServer(port);

                    Console.WriteLine("Press ENTER to exit...");
                    Console.ReadLine();
                    cancel.Cancel();
                }
            }
        }
Example #2
0
        public void TestMaxConnectionIdleTime()
        {
            var connection1Established = new ManualResetEventSlim();
            var connection1Lost        = new ManualResetEventSlim();

            var configuration = new SecureTransport.Configuration
            {
                MaxConnectionIdleTime        = TimeSpan.FromSeconds(5),
                CommunicationProtocolVersion = 1,
            };

            using (var cancellationTokenSource = new CancellationTokenSource())
                using (var serverTransport = new SecureTransport(configuration, null, cancellationTokenSource.Token))
                {
                    serverTransport.StartServer(this.serverListenPort);

                    using (var clientTransport1 = CreateTransport())
                    {
                        serverTransport.OnNewConnection   = _ => connection1Established.Set();
                        clientTransport1.OnConnectionLost = () => connection1Lost.Set();
                        clientTransport1.StartClient(this.clientEndPoints);
                        connection1Established.Wait();

                        // The connections should be terminated after 5 seconds
                        Trace.TraceInformation("Waiting for connection to be lost");
                        connection1Lost.Wait();
                    }
                }
        }
Example #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TcpCommunicationListener" /> class.
        /// </summary>
        /// <param name="server">RingMaster server</param>
        /// <param name="port">Port where this listener will listen</param>
        /// <param name="uriPublished">The specific uri to listen on</param>
        /// <param name="executor">RingMaster request executor</param>
        /// <param name="instrumentation">Instrumentation consumer</param>
        /// <param name="protocol">The Marshalling protocol</param>
        /// <param name="maximumSupportedProtocolVersion">Maximum supported version</param>
        public TcpCommunicationListener(
            RingMasterServer server,
            int port,
            string uriPublished,
            IRingMasterRequestExecutor executor,
            IRingMasterServerInstrumentation instrumentation,
            ICommunicationProtocol protocol,
            uint maximumSupportedProtocolVersion)
        {
            this.server          = server;
            this.port            = port;
            this.uriPublished    = uriPublished;
            this.instrumentation = instrumentation;
            this.protocol        = protocol;

            var transportConfig = new SecureTransport.Configuration
            {
                UseSecureConnection          = false,
                IsClientCertificateRequired  = false,
                CommunicationProtocolVersion = maximumSupportedProtocolVersion,
            };

            this.transport = new SecureTransport(transportConfig);
            this.executor  = executor;
        }
Example #4
0
        private static SecureTransport CreateTransport(CancellationToken cancellationToken)
        {
            var configuration = new SecureTransport.Configuration
            {
                UseSecureConnection          = false,
                CommunicationProtocolVersion = 1
            };

            return(new SecureTransport(configuration, null, cancellationToken));
        }
        private void ConnectPerformanceTest(ConfigurationSection config, CancellationToken cancellationToken)
        {
            try
            {
                var instrumentation = new ConnectPerformanceInstrumentation(this.MetricsFactory);
                var random          = new Random();

                string connectionString = config.GetStringValue("TargetConnectionString");
                connectionString = Helpers.GetServerAddressIfNotProvided(connectionString);
                IPEndPoint[] endpoints                    = SecureTransport.ParseConnectionString(connectionString);
                string       testPath                     = config.GetStringValue("TestPath");
                int          numConnections               = config.GetIntValue("NumberOfConnections");
                int          maxConcurrentRequests        = config.GetIntValue("MaxConcurrentRequests");
                int          minConnectionLifetimeSeconds = config.GetIntValue("MinConnectionLifetimeSeconds");
                int          maxConnectionLifetimeSeconds = config.GetIntValue("MaxConnectionLifetimeSeconds");

                Func <IRingMasterRequestHandler> createConnection = () =>
                {
                    var connectionConfiguration = new SecureTransport.Configuration
                    {
                        UseSecureConnection          = false,
                        CommunicationProtocolVersion = RingMasterCommunicationProtocol.MaximumSupportedVersion,
                        MaxConnectionLifespan        = TimeSpan.FromSeconds(random.Next(minConnectionLifetimeSeconds, maxConnectionLifetimeSeconds))
                    };

                    var protocol  = new RingMasterCommunicationProtocol();
                    var transport = new SecureTransport(connectionConfiguration, instrumentation, cancellationToken);
                    var client    = new RingMasterClient(protocol, transport);
                    transport.StartClient(endpoints);

                    ConnectionStressServiceEventSource.Log.CreateConnection(
                        connectionConfiguration.UseSecureConnection,
                        connectionConfiguration.CommunicationProtocolVersion,
                        (long)connectionConfiguration.MaxConnectionLifespan.TotalSeconds);

                    client.Exists("/", watcher: null).Wait();
                    return((IRingMasterRequestHandler)client);
                };

                using (var connectPerformanceTest = new ConnectPerformance(instrumentation, maxConcurrentRequests, cancellationToken))
                {
                    ConnectionStressServiceEventSource.Log.ConnectPerformanceTestStarted(testPath, numConnections, minConnectionLifetimeSeconds, maxConnectionLifetimeSeconds);

                    connectPerformanceTest.EstablishConnections(createConnection, numConnections);

                    connectPerformanceTest.QueueRequests(testPath);
                }

                ConnectionStressServiceEventSource.Log.ConnectPerformanceTestCompleted();
            }
            catch (Exception ex)
            {
                ConnectionStressServiceEventSource.Log.ConnectPerformanceTestFailed(ex.ToString());
            }
        }
Example #6
0
        private static SecureTransport CreateTransport(X509Certificate[] clientCertificates, X509Certificate[] serverCertificates)
        {
            var configuration = new SecureTransport.Configuration()
            {
                UseSecureConnection            = true,
                ClientCertificates             = clientCertificates,
                ServerCertificates             = serverCertificates,
                CommunicationProtocolVersion   = 1,
                MustCheckCertificateTrustChain = false,
            };

            return(new SecureTransport(configuration, null, CancellationToken.None));
        }
        private void ConnectPerformanceTest(SecureTransport.Configuration configuration, IPEndPoint[] endpoints, int numConnections)
        {
            var instrumentation = new ConnectPerformanceInstrumentation();
            var random          = new Random();

            int minConnectionLifetimeSeconds = int.Parse(appSettings["ConnectPerformance.MinConnectionLifetimeSeconds"]);
            int maxConnectionLifetimeSeconds = int.Parse(appSettings["ConnectPerformance.MaxConnectionLifetimeSeconds"]);

            Func <IRingMasterRequestHandler> createConnection = () =>
            {
                var connectionConfiguration = new SecureTransport.Configuration
                {
                    UseSecureConnection          = configuration.UseSecureConnection,
                    ClientCertificates           = configuration.ClientCertificates,
                    ServerCertificates           = configuration.ServerCertificates,
                    CommunicationProtocolVersion = configuration.CommunicationProtocolVersion,
                    MaxConnectionLifespan        = TimeSpan.FromSeconds(random.Next(minConnectionLifetimeSeconds, maxConnectionLifetimeSeconds)),
                };

                var protocol  = new RingMasterCommunicationProtocol();
                var transport = new SecureTransport(connectionConfiguration, instrumentation, CancellationToken.None);
                var client    = new RingMasterClient(protocol, transport);
                transport.StartClient(endpoints);

                client.Exists("/", watcher: null).Wait();
                return((IRingMasterRequestHandler)client);
            };

            using (var connectPerformanceTest = new ConnectPerformance(instrumentation, this.MaxConcurrency, CancellationToken.None))
            {
                Trace.TraceInformation($"Connect performance test numConnections={numConnections}, path={this.TestPath}, minConnectionLifetimeSeconds={minConnectionLifetimeSeconds}, maxConnectionLifetimeSeconds={maxConnectionLifetimeSeconds}");

                connectPerformanceTest.EstablishConnections(createConnection, numConnections);

                var task = Task.Run(() => connectPerformanceTest.QueueRequests(this.TestPath));

                long lastSuccessCount = 0;
                var  timer            = Stopwatch.StartNew();
                while (!task.Wait(5000))
                {
                    timer.Stop();
                    long rate = (long)((instrumentation.Success - lastSuccessCount) * 1000) / timer.ElapsedMilliseconds;
                    Trace.TraceInformation($"Connections created={instrumentation.ConnectionCreatedCount}, closed={instrumentation.ConnectionClosedCount}, requestSuccess={instrumentation.Success}, requestFailure={instrumentation.Failure}, rate={rate}");
                    timer.Restart();
                    lastSuccessCount = instrumentation.Success;
                }
            }
        }
Example #8
0
        public static void Setup(TestContext context)
        {
            var            path        = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var            builder     = new ConfigurationBuilder().SetBasePath(Path.GetDirectoryName(path)).AddJsonFile("appSettings.json");
            IConfiguration appSettings = builder.Build();

            Helpers.SetupTraceLog(Path.Combine(appSettings["LogFolder"], "VegaInMemoryPerf.LogPath"));
            log = s => Trace.TraceInformation(s);

            // If a parameter is specified as follows:
            //      te.exe VegaInMemoryPerf.dll /p:ServerAddress=127.0.0.1:99
            if (!context.Properties.ContainsKey("ServerAddress"))
            {
                backendCore   = CreateBackend();
                backendServer = new RingMasterServer(protocol, null, CancellationToken.None);

                var transportConfig = new SecureTransport.Configuration
                {
                    UseSecureConnection          = false,
                    IsClientCertificateRequired  = false,
                    CommunicationProtocolVersion = RingMasterCommunicationProtocol.MaximumSupportedVersion,
                };

                serverTransport = new SecureTransport(transportConfig);

                backendServer.RegisterTransport(serverTransport);
                backendServer.OnInitSession = initRequest =>
                {
                    return(new CoreRequestHandler(backendCore, initRequest));
                };

                serverTransport.StartServer(10009);
                serverAddress = "127.0.0.1:10009";
            }
            else
            {
                serverAddress = context.Properties["ServerAddress"] as string;
            }

            // Read the app settings
            minPayloadSize = int.Parse(appSettings["MinPayloadSize"]);
            maxPayloadSize = int.Parse(appSettings["MaxPayloadSize"]);
            threadCount    = int.Parse(appSettings["ThreadCount"]);
        }
Example #9
0
        public void TestClientCertificateSelectionCallback()
        {
            var certificates = GetLocalCertificates(2);

            X509Certificate[] clientCertificates = new X509Certificate[] { certificates[0] };
            X509Certificate[] serverCertificates = new X509Certificate[] { certificates[1] };

            int port = TestSecureTransport.GetAvailablePort(10000);
            var serverAcceptedClient = new ManualResetEventSlim();
            var clientConnected      = new ManualResetEventSlim();
            var clientCertificateSelectionCallbackCalled = new ManualResetEventSlim();

            var configuration = new SecureTransport.Configuration()
            {
                UseSecureConnection               = true,
                ClientCertificates                = certificates,
                ServerCertificates                = serverCertificates,
                CommunicationProtocolVersion      = 1,
                MustCheckCertificateTrustChain    = false,
                LocalCertificateSelectionCallback = (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) =>
                {
                    clientCertificateSelectionCallbackCalled.Set();
                    return(certificates[0]);
                }
            };

            using (var server = CreateTransport(clientCertificates, serverCertificates))
                using (var client = new SecureTransport(configuration, null, CancellationToken.None))
                {
                    server.OnNewConnection = _ => serverAcceptedClient.Set();
                    client.OnNewConnection = _ => clientConnected.Set();
                    server.StartServer(port);
                    client.StartClient(new IPEndPoint(IPAddress.Loopback, port));

                    serverAcceptedClient.Wait(30000).Should().BeTrue();

                    // Client certificate selection callback must be called before
                    // the client accepts the connection.
                    clientCertificateSelectionCallbackCalled.Wait(3000).Should().BeTrue();
                    clientConnected.Wait(30000).Should().BeTrue();
                }
        }
Example #10
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">Command line arguments</param>
        public static void Main(string[] args)
        {
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            if (args == null || args.Length < 1)
            {
                Trace.TraceError("USAGE: SecureTransportClientTool.exe <connection string> [<request length>]");
                return;
            }

            string connectionString = args[0];
            int    requestLength    = 128;
            int    waitTimeoutMs    = 30000;

            if (args.Length > 1)
            {
                requestLength = int.Parse(args[1]);
            }

            var path        = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var builder     = new ConfigurationBuilder().SetBasePath(Path.GetDirectoryName(path)).AddJsonFile("appSettings.json");
            var appSettings = builder.Build();

            var configuration         = new SecureTransport.Configuration();
            int maxConcurrentRequests = int.Parse(appSettings["MaxConcurrentRequests"]);

            configuration.SendBufferSize    = int.Parse(appSettings["SendBufferSize"]);
            configuration.ReceiveBufferSize = int.Parse(appSettings["ReceiveBufferSize"]);

            configuration.UseSecureConnection = bool.Parse(appSettings["SSL.UseSSL"]);
            if (configuration.UseSecureConnection)
            {
                string[] clientThumbprints  = appSettings["SSL.ClientCerts"].Split(new char[] { ';', ',' });
                string[] serviceThumbprints = appSettings["SSL.ServerCerts"].Split(new char[] { ';', ',' });

                configuration.ClientCertificates = SecureTransport.GetCertificatesFromThumbPrintOrFileName(clientThumbprints);
                configuration.ServerCertificates = SecureTransport.GetCertificatesFromThumbPrintOrFileName(serviceThumbprints);
            }

            Trace.TraceInformation(
                "Connecting to {0}.  Using SSL={1} RequestLength={2} MaxConcurrentRequests={3}, SendBufferSize={4}, ReceiveBufferSize={5}",
                connectionString,
                configuration.UseSecureConnection,
                requestLength,
                maxConcurrentRequests,
                configuration.SendBufferSize,
                configuration.ReceiveBufferSize);

            var connectionAvailable = new ManualResetEvent(false);

            IPEndPoint[] endpoints = SecureTransport.ParseConnectionString(connectionString);

            using (var transport = new SecureTransport(configuration))
            {
                transport.StartClient(endpoints);

                Console.CancelKeyPress += (sender, eventArgs) =>
                {
                    Trace.TraceInformation("Attempting to close client transport");
                    transport.Close();
                };

                IConnection currentConnection = null;
                transport.OnNewConnection = connection =>
                {
                    currentConnection = connection;
                    connectionAvailable.Set();
                };

                transport.OnConnectionLost = () =>
                {
                    connectionAvailable.Reset();
                };

                var random = new Random();
                var timer  = new Stopwatch();
                timer.Start();
                long requestsSent = 0;

                byte[] request = new byte[requestLength];
                random.NextBytes(request);

                var sendSemaphore = new SemaphoreSlim(maxConcurrentRequests, maxConcurrentRequests);

                while (true)
                {
                    if (!connectionAvailable.WaitOne(waitTimeoutMs))
                    {
                        Trace.TraceWarning("Connection is not available. retrying...");
                        continue;
                    }

                    currentConnection.OnPacketReceived = packet =>
                    {
                    };

                    try
                    {
                        if (!sendSemaphore.Wait(waitTimeoutMs))
                        {
                            Trace.TraceError("Timedout waiting for send semaphore...");
                            continue;
                        }

                        currentConnection.SendAsync(request).ContinueWith(_ => sendSemaphore.Release());
                    }
                    catch (IOException ex)
                    {
                        Trace.TraceError("IO Exception: {0}", ex.Message);
                    }

                    Interlocked.Increment(ref requestsSent);
                    if (timer.ElapsedMilliseconds > 5000)
                    {
                        long rate          = (requestsSent * 1000) / timer.ElapsedMilliseconds;
                        int  inflightCount = maxConcurrentRequests - sendSemaphore.CurrentCount;
                        Trace.TraceInformation($"Send rate={rate} InFlight={inflightCount}");
                        requestsSent = 0;
                        timer.Restart();
                    }
                }
            }
        }
Example #11
0
        public RingMasterClient(
            ServerSpec serverSpec,
            Configuration configuration,
            IRingMasterClientInstrumentation instrumentation,
            IWatcher watcher,
            CancellationToken cancellationToken)
        {
            if (serverSpec == null)
            {
                throw new ArgumentNullException(nameof(serverSpec));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            IPEndPoint[] endpoints = serverSpec.Endpoints;
            if ((endpoints == null) || (endpoints.Length == 0))
            {
                throw new ArgumentException("Endpoints were not specified");
            }

            if (watcher != null)
            {
                this.SetWatcher(watcher);
            }

            SecureTransport secureTransport = null;

            try
            {
                var transportConfiguration = new SecureTransport.Configuration();
                transportConfiguration.UseSecureConnection = serverSpec.UseSecureConnection;
                transportConfiguration.ClientCertificates  = new X509Certificate[] { serverSpec.ClientCertificate };
                transportConfiguration.ServerCertificates  = serverSpec.AcceptedServerCertificates;
                transportConfiguration.RemoteCertificateValidationCallback = serverSpec.ServerCertificateValidationCallback;
                transportConfiguration.LocalCertificateSelectionCallback   = serverSpec.ClientCertificationSelectionCallback;
                transportConfiguration.MustCheckCertificateRevocation      = serverSpec.MustCheckCertificateRevocation;
                transportConfiguration.MustCheckCertificateTrustChain      = serverSpec.MustCheckCertificateTrustChain;
                transportConfiguration.CommunicationProtocolVersion        = serverSpec.CommunicationProtocolVersion;
                transportConfiguration.SendBufferSize    = configuration.BufferSize;
                transportConfiguration.ReceiveBufferSize = configuration.BufferSize;
                transportConfiguration.SendQueueLength   = configuration.RequestQueueLength;
                transportConfiguration.AuthAsClient      = true;

                List <SecureTransport.SubjectRuleValidation> subjectRules = new List <SecureTransport.SubjectRuleValidation>();

                if (!string.IsNullOrWhiteSpace(serverSpec.CertValidationASubject) && serverSpec.CertValidationASigningThumbprints != null)
                {
                    SecureTransport.SubjectValidation subjectA = new SecureTransport.SubjectValidation()
                    {
                        CertificateSubject     = serverSpec.CertValidationASubject,
                        SigningCertThumbprints = serverSpec.CertValidationASigningThumbprints,
                    };
                    subjectRules.Add(new SecureTransport.SubjectRuleValidation(CertificateRules.AbstractCertificateRule.RoleToApply.ServerCert, subjectA));
                }

                if (!string.IsNullOrWhiteSpace(serverSpec.CertValidationBSubject) && serverSpec.CertValidationBSigningThumbprints != null)
                {
                    SecureTransport.SubjectValidation subjectB = new SecureTransport.SubjectValidation()
                    {
                        CertificateSubject     = serverSpec.CertValidationBSubject,
                        SigningCertThumbprints = serverSpec.CertValidationBSigningThumbprints,
                    };
                    subjectRules.Add(new SecureTransport.SubjectRuleValidation(CertificateRules.AbstractCertificateRule.RoleToApply.ServerCert, subjectB));
                }

                if (subjectRules != null && subjectRules.Count > 0)
                {
                    transportConfiguration.SubjectValidations = subjectRules;
                }

                secureTransport = new SecureTransport(transportConfiguration, instrumentation: null, cancellationToken: cancellationToken);

                ICommunicationProtocol protocol = new RingMasterCommunicationProtocol();

                var handlerConfiguration = new RingMasterRequestHandler.Configuration();

                handlerConfiguration.DefaultTimeout     = configuration.DefaultTimeout;
                handlerConfiguration.HeartBeatInterval  = configuration.HeartBeatInterval;
                handlerConfiguration.RequestQueueLength = configuration.RequestQueueLength;
                handlerConfiguration.RequireLockForReadOnlyOperations = configuration.RequireLockForReadOnlyOperations;
                handlerConfiguration.MustTransparentlyForwardRequests = configuration.MustTransparentlyForwardRequests;

                var handlerInstrumentation = new RingMasterRequestHandlerInstrumentation(instrumentation);

                this.requestHandler = new RingMasterRequestHandler(
                    handlerConfiguration,
                    handlerInstrumentation,
                    protocol,
                    secureTransport,
                    cancellationToken);

                foreach (var endpoint in endpoints)
                {
                    RingMasterClientEventSource.Log.Start(endpoint.ToString());
                }

                secureTransport.StartClient(endpoints);
                secureTransport = null;
            }
            finally
            {
                if (secureTransport != null)
                {
                    secureTransport.Dispose();
                }
            }
        }
Example #12
0
        /// <summary>
        /// Entry point
        /// </summary>
        /// <param name="args">Arguments provided to the program</param>
        public static void Main(string[] args)
        {
            string testType          = "getdata";
            string ringMasterAddress = "127.0.0.1:99";
            string path = "/Performance";

            var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var builder      = new ConfigurationBuilder().SetBasePath(Path.GetDirectoryName(assemblyPath)).AddJsonFile("appSettings.json");

            appSettings = builder.Build();

            if (args.Length > 0)
            {
                testType = args[0].ToLower();
            }

            if (args.Length > 1)
            {
                ringMasterAddress = args[1];
            }

            if (args.Length > 2)
            {
                path = args[2];
            }

            bool useSecureConnection = false;

            X509Certificate[] clientCertificates         = null;
            X509Certificate[] acceptedServerCertificates = null;

            if (bool.Parse(appSettings["SSL.UseSSL"]))
            {
                useSecureConnection = true;
                string[] clientCertificateThumbprints = appSettings["SSL.ClientCerts"].Split(new char[] { ';', ',' });
                clientCertificates         = RingMasterClient.GetCertificatesFromThumbPrintOrFileName(clientCertificateThumbprints);
                acceptedServerCertificates = Certificates.GetDecodedCertificates(appSettings["SSL.ServerCerts"]);

                foreach (var certificate in clientCertificates)
                {
                    Trace.TraceInformation($"Client certificate: subject={certificate.Subject} thumbprint={certificate.GetCertHashString()}");
                }

                foreach (var certificate in acceptedServerCertificates)
                {
                    Trace.TraceInformation($"Server certificate: subject={certificate.Subject} thumbprint={certificate.GetCertHashString()}");
                }
            }
            else
            {
                Trace.TraceInformation("Not using SSL");
            }

            var performanceTest = new RingMasterPerformance();

            performanceTest.TestPath                       = path;
            performanceTest.TimeStreamId                   = ulong.Parse(appSettings["TimeStream"]);
            performanceTest.MaxConcurrency                 = int.Parse(appSettings["MaxConcurrency"]);
            performanceTest.MaxDataSize                    = int.Parse(appSettings["MaxDataSize"]);
            performanceTest.MinDataSize                    = int.Parse(appSettings["MinDataSize"]);
            performanceTest.MinChildrenPerNode             = int.Parse(appSettings["MinChildrenPerNode"]);
            performanceTest.MaxChildrenPerNode             = int.Parse(appSettings["MaxChildrenPerNode"]);
            performanceTest.BatchLength                    = int.Parse(appSettings["BatchLength"]);
            performanceTest.MaxAllowedCodePoint            = int.Parse(appSettings["MaxAllowedCodePoint"]);
            performanceTest.MaxGetChildrenEnumerationCount = int.Parse(appSettings["MaxGetChildrenEnumerationCount"]);
            performanceTest.MaxSetOperations               = int.Parse(appSettings["MaxSetOperations"]);
            performanceTest.MaxNodes                       = int.Parse(appSettings["MaxNodes"]);
            performanceTest.TestMaxRunTimeInSeconds        = int.Parse(appSettings["TestMaxRunTimeInSeconds"]);

            int requestTimeout = int.Parse(appSettings["RequestTimeout"]);

            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            var serverSpec = new RingMasterClient.ServerSpec
            {
                Endpoints           = SecureTransport.ParseConnectionString(ringMasterAddress),
                UseSecureConnection = useSecureConnection,
            };

            if (useSecureConnection)
            {
                serverSpec.ClientCertificate              = clientCertificates[0];
                serverSpec.AcceptedServerCertificates     = acceptedServerCertificates;
                serverSpec.MustCheckCertificateRevocation = false;
                serverSpec.MustCheckCertificateTrustChain = false;
            }

            var clientConfiguration = new RingMasterClient.Configuration
            {
                DefaultTimeout = TimeSpan.FromMilliseconds(requestTimeout),
            };

            var cancellation = new CancellationTokenSource();

            cancellation.CancelAfter(TimeSpan.FromSeconds(performanceTest.TestMaxRunTimeInSeconds));

            try
            {
                using (var client = new RingMasterClient(serverSpec, clientConfiguration, instrumentation: null, watcher: null, cancellationToken: CancellationToken.None))
                    using (var ringMaster = client.OpenTimeStream(performanceTest.TimeStreamId))
                    {
                        if (testType == "setdata")
                        {
                            performanceTest.SetDataPerformanceTest(ringMaster).Wait();
                        }
                        else if (testType == "create")
                        {
                            int numNodes = 500000;

                            if (args.Length > 3)
                            {
                                numNodes = int.Parse(args[3]);
                            }

                            performanceTest.CreatePerformanceTest(ringMaster, numNodes);
                        }
                        else if (testType == "createflat")
                        {
                            int numNodes = 1000000;

                            if (args.Length > 3)
                            {
                                numNodes = int.Parse(args[3]);
                            }

                            performanceTest.CreateFlatPerformanceTest(ringMaster, numNodes);
                        }
                        else if (testType == "getchildren")
                        {
                            int maxChildren = 1000;

                            if (args.Length > 3)
                            {
                                maxChildren = int.Parse(args[3]);
                            }

                            performanceTest.GetChildrenPerformanceTest(ringMaster, maxChildren);
                        }
                        else if (testType == "delete")
                        {
                            performanceTest.DeletePerformanceTest(ringMaster).Wait();
                        }
                        else if (testType == "scheduleddelete")
                        {
                            performanceTest.ScheduledDeletePerformanceTest(ringMaster);
                        }
                        else if (testType == "connect")
                        {
                            int numConnections = 100;

                            if (args.Length > 3)
                            {
                                numConnections = int.Parse(args[3]);
                            }

                            var configuration = new SecureTransport.Configuration
                            {
                                UseSecureConnection          = useSecureConnection,
                                ClientCertificates           = clientCertificates,
                                ServerCertificates           = acceptedServerCertificates,
                                CommunicationProtocolVersion = RingMasterCommunicationProtocol.MaximumSupportedVersion,
                            };

                            IPEndPoint[] endpoints = SecureTransport.ParseConnectionString(ringMasterAddress);

                            performanceTest.ConnectPerformanceTest(configuration, endpoints, numConnections);
                        }
                        else if (testType == "exists")
                        {
                            performanceTest.ExistsPerformanceTest(ringMaster).Wait();
                        }
                        else if (testType == "watchers")
                        {
                            int maxWatchers = 1000;
                            if (args.Length > 3)
                            {
                                maxWatchers = int.Parse(args[3]);
                            }

                            performanceTest.WatcherPerformanceTest(ringMaster, maxWatchers, cancellation).Wait();
                        }
                        else
                        {
                            performanceTest.GetDataPerformanceTest(ringMaster, cancellation).Wait();
                        }
                    }
            }
            catch (OperationCanceledException)
            {
            }
            catch (AggregateException ex)
            {
                if (!ex.Flatten().InnerExceptions.Any(e => e is OperationCanceledException))
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">Command line arguments</param>
        public static void Main(string[] args)
        {
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            if (args == null || args.Length < 1)
            {
                Trace.TraceError("USAGE: SecureTransportServiceTool.exe <port>");
                return;
            }

            int port = int.Parse(args[0]);

            var configuration = new SecureTransport.Configuration();

            var            path        = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var            builder     = new ConfigurationBuilder().SetBasePath(Path.GetDirectoryName(path)).AddJsonFile("appSettings.json");
            IConfiguration appSettings = builder.Build();

            int maxConcurrentRequests = int.Parse(appSettings["MaxConcurrentRequests"]);

            configuration.UseSecureConnection = bool.Parse(appSettings["SSL.UseSSL"]);
            configuration.SendBufferSize      = int.Parse(appSettings["SendBufferSize"]);
            configuration.ReceiveBufferSize   = int.Parse(appSettings["ReceiveBufferSize"]);

            if (configuration.UseSecureConnection)
            {
                string[] clientThumbprints  = appSettings["SSL.ClientCerts"].Split(new char[] { ';', ',' });
                string[] serviceThumbprints = appSettings["SSL.ServerCerts"].Split(new char[] { ';', ',' });

                configuration.ClientCertificates = SecureTransport.GetCertificatesFromThumbPrintOrFileName(clientThumbprints);
                configuration.ServerCertificates = SecureTransport.GetCertificatesFromThumbPrintOrFileName(serviceThumbprints);
            }

            Trace.TraceInformation(
                "Listening on port {0}. Using SSL={1}, MaxConcurentRequests={2}, SendBufferSize={3}, ReceiveBufferSize={4}",
                port,
                configuration.UseSecureConnection,
                maxConcurrentRequests,
                configuration.SendBufferSize,
                configuration.ReceiveBufferSize);

            using (var transport = new SecureTransport(configuration))
            {
                var  timer             = Stopwatch.StartNew();
                long activeConnections = 0;
                long packetsReceived   = 0;
                Task serverTask        = transport.StartServer(port);

                Console.CancelKeyPress += (sender, eventArgs) =>
                {
                    Trace.TraceInformation("Attempting to close server transport");
                    transport.Close();
                };

                var semaphore = new SemaphoreSlim(maxConcurrentRequests, maxConcurrentRequests);
                transport.OnNewConnection = connection =>
                {
                    Trace.TraceInformation("Connection Established with {0}", connection.RemoteEndPoint);
                    Interlocked.Increment(ref activeConnections);

                    connection.OnPacketReceived = packet =>
                    {
                        semaphore.Wait();
                        Interlocked.Increment(ref packetsReceived);
                        connection.SendAsync(packet).ContinueWith(_ => semaphore.Release());
                    };

                    connection.OnConnectionLost = () =>
                    {
                        Trace.TraceInformation("Connection with {0} was lost", connection.RemoteEndPoint);
                        Interlocked.Decrement(ref activeConnections);
                    };
                };

                while (!serverTask.Wait(5000))
                {
                    timer.Stop();
                    long rate          = (long)(packetsReceived * 1000) / timer.ElapsedMilliseconds;
                    int  inflightCount = maxConcurrentRequests - semaphore.CurrentCount;
                    Trace.TraceInformation($"ActiveConnections={activeConnections}, RequestRate {rate} InFlight count={inflightCount}");
                    packetsReceived = 0;
                    timer.Restart();
                }
            }
        }