private void WriteFlood(CommandProcessorContext context, WriteFloodStats stats, int clientsCnt, long requestsCnt, int streamsCnt,
                                int size, int batchSize, string streamNamePrefix, RequestMonitor monitor)
        {
            context.IsAsync();

            var doneEvent = new ManualResetEventSlim(false);
            var clients   = new List <TcpTypedConnection <byte[]> >();
            var threads   = new List <Thread>();

            long last = 0;

            string[] streams = Enumerable.Range(0, streamsCnt).Select(x =>
                                                                      string.IsNullOrWhiteSpace(streamNamePrefix)
                                        ? Guid.NewGuid().ToString()
                                        : $"{streamNamePrefix}-{x}"
                                                                      ).ToArray();

            context.Log.Information("Writing streams randomly between {first} and {last}",
                                    streams.FirstOrDefault(),
                                    streams.LastOrDefault());

            Console.WriteLine($"Last stream: {streams.LastOrDefault()}");
            stats.StartTime = DateTime.UtcNow;
            var sw2 = new Stopwatch();

            for (int i = 0; i < clientsCnt; i++)
            {
                var  count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long sent     = 0;
                long received = 0;
                var  rnd      = new Random();
                var  client   = context._tcpTestClient.CreateTcpConnection(
                    context,
                    (conn, pkg) => {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize <TcpClientMessageDto.WriteEventsCompleted>();
                    monitor.EndOperation(pkg.CorrelationId);
                    switch (dto.Result)
                    {
                    case TcpClientMessageDto.OperationResult.Success:
                        Interlocked.Add(ref stats.Succ, batchSize);
                        if (stats.Succ - last > 1000)
                        {
                            last = stats.Succ;
                            Console.Write(".");
                        }

                        break;

                    case TcpClientMessageDto.OperationResult.PrepareTimeout:
                        Interlocked.Increment(ref stats.PrepTimeout);
                        break;

                    case TcpClientMessageDto.OperationResult.CommitTimeout:
                        Interlocked.Increment(ref stats.CommitTimeout);
                        break;

                    case TcpClientMessageDto.OperationResult.ForwardTimeout:
                        Interlocked.Increment(ref stats.ForwardTimeout);
                        break;

                    case TcpClientMessageDto.OperationResult.WrongExpectedVersion:
                        Interlocked.Increment(ref stats.WrongExpVersion);
                        break;

                    case TcpClientMessageDto.OperationResult.StreamDeleted:
                        Interlocked.Increment(ref stats.StreamDeleted);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    if (dto.Result != TcpClientMessageDto.OperationResult.Success)
                    {
                        if (Interlocked.Increment(ref stats.Fail) % 1000 == 0)
                        {
                            Console.Write('#');
                        }
                    }
                    Interlocked.Increment(ref received);
                    var localAll = Interlocked.Add(ref stats.All, batchSize);
                    if (localAll % 100000 == 0)
                    {
                        stats.Elapsed = sw2.Elapsed;
                        stats.Rate    = 1000.0 * 100000 / stats.Elapsed.TotalMilliseconds;
                        sw2.Restart();
                        context.Log.Debug(
                            "\nDONE TOTAL {writes} WRITES IN {elapsed} ({rate:0.0}/s) [S:{success}, F:{failures} (WEV:{wrongExpectedVersion}, " +
                            "P:{prepareTimeout}, C:{commitTimeout}, F:{forwardTimeout}, D:{streamDeleted})].",
                            localAll, stats.Elapsed, stats.Rate, stats.Succ, stats.Fail,
                            stats.WrongExpVersion, stats.PrepTimeout, stats.CommitTimeout, stats.ForwardTimeout, stats.StreamDeleted);
                        stats.WriteStatsToFile(context.StatsLogger);
                    }

                    if (localAll >= requestsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                threads.Add(new Thread(() => {
                    for (int j = 0; j < count; ++j)
                    {
                        var events = new TcpClientMessageDto.NewEvent[batchSize];
                        for (int q = 0; q < batchSize; q++)
                        {
                            events[q] = new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
                                                                         "TakeSomeSpaceEvent",
                                                                         1, 0,
                                                                         Common.Utils.Helper.UTF8NoBom.GetBytes(
                                                                             "{ \"DATA\" : \"" + new string('*', size) + "\"}"),
                                                                         Common.Utils.Helper.UTF8NoBom.GetBytes(
                                                                             "{ \"METADATA\" : \"" + new string('$', 100) + "\"}"));
                        }

                        var corrid = Guid.NewGuid();
                        var write  = new TcpClientMessageDto.WriteEvents(
                            streams[rnd.Next(streamsCnt)],
                            ExpectedVersion.Any,
                            events,
                            false);
                        var package = new TcpPackage(TcpCommand.WriteEvents, corrid, write.Serialize());
                        monitor.StartOperation(corrid);
                        client.EnqueueSend(package.AsByteArray());

                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) >
                               context._tcpTestClient.Options.WriteWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(client => client.Close());

            stats.WriteStatsToFile(context.StatsLogger);
            context.Log.Information(
                "Completed. Successes: {success}, failures: {failures} (WRONG VERSION: {wrongExpectedVersion}, P: {prepareTimeout}, " +
                "C: {commitTimeout}, F: {forwardTimeout}, D: {streamDeleted})",
                stats.Succ, stats.Fail, stats.WrongExpVersion, stats.PrepTimeout, stats.CommitTimeout, stats.ForwardTimeout, stats.StreamDeleted);

            var reqPerSec = (stats.All + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Information("{requests} requests completed in {elapsed}ms ({rate:0.00} reqs per sec).", stats.All,
                                    sw.ElapsedMilliseconds, reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", stats.Succ), PerfUtils.Col("failures", stats.Fail)));

            var failuresRate = (int)(100 * stats.Fail / (stats.Fail + stats.Succ));

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), failuresRate);
            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-c{1}-r{2}-st{3}-s{4}-reqPerSec", Keyword, clientsCnt, requestsCnt, streamsCnt, size),
                (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-c{1}-r{2}-st{3}-s{4}-failureSuccessRate", Keyword, clientsCnt, requestsCnt,
                              streamsCnt, size), failuresRate);
            monitor.GetMeasurementDetails();
            if (Interlocked.Read(ref stats.Succ) != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
Example #2
0
        private void PingFlood(CommandProcessorContext context, int clientsCnt, int requestsCnt)
        {
            context.IsAsync();

            var threads        = new List <Thread>();
            var autoResetEvent = new AutoResetEvent(false);

            var all = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);

                int sent     = 0;
                int received = 0;

                threads.Add(new Thread(() =>
                {
                    var client = new HttpAsyncClient();
                    var url    = context.Client.HttpEndpoint.ToHttpUrl("/ping");

                    Action <HttpResponse> onsuccess = response =>
                    {
                        Interlocked.Increment(ref received);
                        var pongs = Interlocked.Increment(ref all);

                        if (pongs % 1000 == 0)
                        {
                            Console.Write('.');
                        }

                        if (pongs == requestsCnt)
                        {
                            autoResetEvent.Set();
                        }
                    };

                    Action <Exception> onException = e =>
                    {
                        context.Log.ErrorException(e, "Error during GET");
                        var pongs = Interlocked.Increment(ref all);
                        if (pongs == requestsCnt)
                        {
                            autoResetEvent.Set();
                        }
                    };

                    for (int j = 0; j < count; ++j)
                    {
                        client.Get(url, onsuccess, onException);
                        Interlocked.Increment(ref sent);
                        while (sent - received > context.Client.Options.PingWindow)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            var sw = Stopwatch.StartNew();

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();
            sw.Stop();

            var reqPerSec = (requestsCnt + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds))
                );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            context.Success();
        }
        private void PingFlood(CommandProcessorContext context, int clientsCnt, int requestsCnt)
        {
            context.IsAsync();

            var autoResetEvent = new AutoResetEvent(false);
            var clients        = new List <TcpTypedConnection <byte[]> >();
            var threads        = new List <Thread>();
            var all            = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                int sent     = 0;
                int received = 0;

                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, msg) =>
                {
                    Interlocked.Increment(ref received);
                    var pongs = Interlocked.Increment(ref all);
                    if (pongs % 10000 == 0)
                    {
                        Console.Write('.');
                    }
                    if (pongs == requestsCnt)
                    {
                        autoResetEvent.Set();
                    }
                },
                    connectionClosed: (conn, err) =>
                {
                    if (all < requestsCnt)
                    {
                        context.Fail(null, "Socket was closed, but not all requests were completed.");
                    }
                    else
                    {
                        context.Success();
                    }
                });

                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        //TODO GFY PING NEEDS CORRELATION ID
                        var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), Payload);
                        client.EnqueueSend(package.AsByteArray());
                        Interlocked.Increment(ref sent);

                        while (sent - received > context.Client.Options.PingWindow)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            var sw = Stopwatch.StartNew();

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();
            sw.Stop();

            foreach (var client in clients)
            {
                client.Close();
            }

            var reqPerSec = (requestsCnt + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds))
                );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            context.Success();
        }
        private void WriteFlood(CommandProcessorContext context, int clientsCnt, long requestsCnt, int streamsCnt, int size)
        {
            context.IsAsync();

            var doneEvent = new ManualResetEventSlim(false);
            var clients   = new List <IEventStoreConnection>();
            var threads   = new List <Thread>();

            long succ = 0;

            var streams = Enumerable.Range(0, streamsCnt).Select(x => Guid.NewGuid().ToString()).ToArray();
            var sw2     = new Stopwatch();

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                var rnd   = new Random();

                var settings = ConnectionSettings.Create()
                               .UseConsoleLogger()
                               .PerformOnAnyNode()
                               .LimitReconnectionsTo(10)
                               .LimitRetriesForOperationTo(10)
                               .LimitOperationsQueueTo(10000)
                               .LimitConcurrentOperationsTo(context.Client.Options.WriteWindow / clientsCnt)
                               .FailOnNoServerResponse();

                var client = EventStoreConnection.Create(settings, new Uri(string.Format("tcp://{0}:{1}", context.Client.TcpEndpoint.Address, context.Client.TcpEndpoint.Port)));
                clients.Add(client);

                threads.Add(new Thread(_ =>
                {
                    client.ErrorOccurred += (s, e) => context.Fail(e.Exception, "Error on connection");
                    client.ConnectAsync().Wait();

                    for (int j = 0; j < count; ++j)
                    {
                        var task = client.AppendToStreamAsync(streams[rnd.Next(streamsCnt)],
                                                              ExpectedVersion.Any,
                                                              new EventData(Guid.NewGuid(),
                                                                            "TakeSomeSpaceEvent",
                                                                            false,
                                                                            Common.Utils.Helper.UTF8NoBom.GetBytes("DATA" + new string('*', size)),
                                                                            Common.Utils.Helper.UTF8NoBom.GetBytes("METADATA" + new string('$', 100))));
                        task.ContinueWith(x =>
                        {
                            if (x.IsFaulted)
                            {
                                context.Fail(x.Exception.InnerException, "Error on writing operation.");
                                return;
                            }

                            var localAll = Interlocked.Increment(ref succ);
                            if (localAll % 1000 == 0)
                            {
                                Console.Write('.');
                            }
                            if (localAll % 100000 == 0)
                            {
                                var elapsed = sw2.Elapsed;
                                sw2.Restart();
                                context.Log.Trace("\nDONE TOTAL {0} WRITES IN {1} ({2:0.0}/s).",
                                                  localAll,
                                                  elapsed,
                                                  1000.0 * 100000 / elapsed.TotalMilliseconds);
                            }
                            if (localAll == requestsCnt)
                            {
                                context.Success();
                                doneEvent.Set();
                            }
                        });
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            clients.ForEach(x => x.Close());
            sw.Stop();

            context.Log.Info("Completed. Successes: {0}.", succ);

            var reqPerSec = (succ + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", succ, sw.ElapsedMilliseconds, reqPerSec);

            var fail = requestsCnt - succ;

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));
            var failuresRate = (int)(100 * fail / (fail + succ));

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), failuresRate);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-reqPerSec", Keyword, clientsCnt, requestsCnt, streamsCnt, size), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-failureSuccessRate", Keyword, clientsCnt, requestsCnt, streamsCnt, size), failuresRate);

            if (Interlocked.Read(ref succ) != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
Example #5
0
        private void PingFlood(CommandProcessorContext context, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var  threads   = new List <Thread>();
            var  doneEvent = new ManualResetEventSlim(false);
            long all       = 0;
            long succ      = 0;
            long fail      = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var  count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long received = 0;
                long sent     = 0;
                threads.Add(new Thread(() =>
                {
                    var client = new HttpAsyncClient();
                    var url    = context.Client.HttpEndpoint.ToHttpUrl("/ping");

                    Action <HttpResponse> onSuccess = response =>
                    {
                        Interlocked.Increment(ref received);
                        if (Interlocked.Increment(ref succ) % 1000 == 0)
                        {
                            Console.Write('.');
                        }
                        if (Interlocked.Increment(ref all) == requestsCnt)
                        {
                            doneEvent.Set();
                        }
                    };

                    Action <Exception> onException = e =>
                    {
                        context.Log.ErrorException(e, "Error during GET");
                        Interlocked.Increment(ref received);
                        if (Interlocked.Increment(ref fail) % 1000 == 0)
                        {
                            Console.Write('#');
                        }
                        if (Interlocked.Increment(ref all) == requestsCnt)
                        {
                            doneEvent.Set();
                        }
                    };

                    for (int j = 0; j < count; ++j)
                    {
                        client.Get(url, TimeSpan.FromMilliseconds(10000), onSuccess, onException);
                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) > context.Client.Options.PingWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);

            if (Interlocked.Read(ref succ) == requestsCnt)
            {
                context.Success();
            }
            else
            {
                context.Fail();
            }
        }
        private void ReadFlood(CommandProcessorContext context, string eventStreamId, int clientsCnt, long requestsCnt,
                               bool resolveLinkTos, bool requireLeader, RequestMonitor monitor)
        {
            context.IsAsync();

            var  clients   = new List <TcpTypedConnection <byte[]> >();
            var  threads   = new List <Thread>();
            var  doneEvent = new ManualResetEventSlim(false);
            var  sw2       = new Stopwatch();
            long succ      = 0;
            long fail      = 0;
            long all       = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var  count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long received = 0;
                long sent     = 0;
                var  client   = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) => {
                    if (pkg.Command != TcpCommand.ReadEventCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize <TcpClientMessageDto.ReadEventCompleted>();
                    monitor.EndOperation(pkg.CorrelationId);
                    if (dto.Result == TcpClientMessageDto.ReadEventCompleted.ReadEventResult.Success)
                    {
                        if (Interlocked.Increment(ref succ) % 1000 == 0)
                        {
                            Console.Write(".");
                        }
                    }
                    else
                    {
                        if (Interlocked.Increment(ref fail) % 1000 == 0)
                        {
                            Console.Write("#");
                        }
                    }

                    Interlocked.Increment(ref received);
                    var localAll = Interlocked.Increment(ref all);
                    if (localAll % 100000 == 0)
                    {
                        var elapsed = sw2.Elapsed;
                        sw2.Restart();
                        context.Log.Verbose("\nDONE TOTAL {reads} READS IN {elapsed} ({rate:0.0}/s).", localAll,
                                            elapsed, 1000.0 * 100000 / elapsed.TotalMilliseconds);
                    }

                    if (localAll == requestsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                threads.Add(new Thread(() => {
                    for (int j = 0; j < count; ++j)
                    {
                        var corrId  = Guid.NewGuid();
                        var read    = new TcpClientMessageDto.ReadEvent(eventStreamId, 0, resolveLinkTos, requireLeader);
                        var package = new TcpPackage(TcpCommand.ReadEvent, corrId, read.Serialize());
                        monitor.StartOperation(corrId);
                        client.EnqueueSend(package.AsByteArray());

                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) >
                               context.Client.Options.ReadWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(client => client.Close());

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Information("Completed. READS succ: {success}, fail: {failures}.", Interlocked.Read(ref succ),
                                    Interlocked.Read(ref fail));
            context.Log.Information("{requests} requests completed in {elapsed}ms ({rate:0.00} reqs per sec).", all,
                                    sw.ElapsedMilliseconds, reqPerSec);
            monitor.GetMeasurementDetails();
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                              PerfUtils.Row(PerfUtils.Col("readsCnt", all)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            if (succ != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
Example #7
0
        private void WriteFlood(CommandProcessorContext context, int clientsCnt, long requestsCnt, int streamsCnt)
        {
            context.IsAsync();

            var doneEvent = new AutoResetEvent(false);
            var clients   = new List <TcpTypedConnection <byte[]> >();
            var threads   = new List <Thread>();

            long succ            = 0;
            long fail            = 0;
            long prepTimeout     = 0;
            long commitTimeout   = 0;
            long forwardTimeout  = 0;
            long wrongExpVersion = 0;
            long streamDeleted   = 0;
            long all             = 0;

            var streams = Enumerable.Range(0, streamsCnt).Select(x => Guid.NewGuid().ToString()).ToArray();
            var sw2     = new Stopwatch();

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);

                int sent     = 0;
                int received = 0;
                var rnd      = new Random();

                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize <ClientMessageDto.WriteEventsCompleted>();
                    switch ((OperationErrorCode)dto.ErrorCode)
                    {
                    case OperationErrorCode.Success:
                        Interlocked.Increment(ref succ);
                        break;

                    case OperationErrorCode.PrepareTimeout:
                        Interlocked.Increment(ref prepTimeout);
                        break;

                    case OperationErrorCode.CommitTimeout:
                        Interlocked.Increment(ref commitTimeout);
                        break;

                    case OperationErrorCode.ForwardTimeout:
                        Interlocked.Increment(ref forwardTimeout);
                        break;

                    case OperationErrorCode.WrongExpectedVersion:
                        Interlocked.Increment(ref wrongExpVersion);
                        break;

                    case OperationErrorCode.StreamDeleted:
                        Interlocked.Increment(ref streamDeleted);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    if (dto.ErrorCode != (int)OperationErrorCode.Success)
                    {
                        Interlocked.Increment(ref fail);
                    }

                    Interlocked.Increment(ref received);

                    var localAll = Interlocked.Increment(ref all);
                    if (localAll % 1000 == 0)
                    {
                        Console.Write(".");
                    }
                    if (localAll % 100000 == 0)
                    {
                        var elapsed = sw2.Elapsed;
                        sw2.Restart();
                        context.Log.Trace("\nDONE TOTAL {0} WRITES IN {1} ({2:0.0}/s).",
                                          localAll,
                                          elapsed,
                                          1000.0 * 100000 / elapsed.TotalMilliseconds);
                    }
                    if (localAll == requestsCnt)
                    {
                        doneEvent.Set();
                    }
                },
                    connectionClosed: (conn, err) =>
                {
                    if (all < requestsCnt)
                    {
                        context.Fail(null, "Socket was closed, but not all requests were completed.");
                    }
                    else
                    {
                        context.Success();
                    }
                });

                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var write = new ClientMessageDto.WriteEvents(
                            Guid.Empty,
                            streams[rnd.Next(streamsCnt)],
                            ExpectedVersion.Any,
                            new[] {
                            new ClientMessageDto.Event(Guid.NewGuid(),
                                                       "TakeSomeSpaceEvent",
                                                       Encoding.UTF8.GetBytes("DATA" + new string('*', 256)),
                                                       Encoding.UTF8.GetBytes("METADATA" + new string('$', 100)))
                        });
                        var package = new TcpPackage(TcpCommand.WriteEvents, write.Serialize());
                        client.EnqueueSend(package.AsByteArray());

                        Interlocked.Increment(ref sent);
                        while (sent - received > context.Client.Options.WriteWindow)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }
            doneEvent.WaitOne();
            sw.Stop();

            foreach (var client in clients)
            {
                client.Close();
            }

            context.Log.Info("Completed. Successes: {0}, failures: {1} (WRONG VERSION: {2}, P: {3}, C: {4}, F: {5}, D: {6})",
                             succ,
                             fail,
                             wrongExpVersion,
                             prepTimeout,
                             commitTimeout,
                             forwardTimeout,
                             streamDeleted);

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             all,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt),
                100 * fail / (fail + succ));

            context.Success();
        }
        private void ReadFlood(CommandProcessorContext context, string eventStreamId, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var  threads   = new List <Thread>();
            var  doneEvent = new ManualResetEventSlim(false);
            long succ      = 0;
            long fail      = 0;
            long all       = 0;

            var sw2 = new Stopwatch();

            for (int i = 0; i < clientsCnt; i++)
            {
                var  count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long sent     = 0;
                long received = 0;
                threads.Add(new Thread(() =>
                {
                    var client = new HttpAsyncClient();
                    var url    = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}/{1}?format=json", eventStreamId, 0);

                    Action onReceived = () =>
                    {
                        Interlocked.Increment(ref received);
                        var localAll = Interlocked.Increment(ref all);
                        if (localAll % 10000 == 0)
                        {
                            var elapsed = sw2.Elapsed;
                            sw2.Restart();
                            context.Log.Trace("\nDONE TOTAL {0} READS IN {1} ({2:0.0}/s).", localAll, elapsed, 1000.0 * 10000 / elapsed.TotalMilliseconds);
                        }
                        if (localAll == requestsCnt)
                        {
                            doneEvent.Set();
                        }
                    };

                    Action <HttpResponse> onSuccess = response =>
                    {
                        if (Interlocked.Increment(ref succ) % 100 == 0)
                        {
                            Console.Write(".");
                        }
                        onReceived();
                    };

                    Action <Exception> onException = exc =>
                    {
                        context.Log.ErrorException(exc, "Error during GET");
                        if (Interlocked.Increment(ref fail) % 100 == 0)
                        {
                            Console.Write("#");
                        }
                        onReceived();
                    };

                    for (int j = 0; j < count; ++j)
                    {
                        client.Get(url, TimeSpan.FromMilliseconds(10000), onSuccess, onException);
                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) > context.Client.Options.ReadWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("Completed. READS succ: {0}, fail: {1}.", Interlocked.Read(ref succ), Interlocked.Read(ref fail));
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                              PerfUtils.Row(PerfUtils.Col("readsCnt", all)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);

            if (Interlocked.Read(ref succ) == requestsCnt)
            {
                context.Success();
            }
            else
            {
                context.Fail();
            }
        }
Example #9
0
        private async Task WriteFlood(CommandProcessorContext context, WriteFloodStats stats, long interval, int clientsCnt, long requestsCnt, int streamsCnt,
                                      int size, int batchSize, string streamNamePrefix, RequestMonitor monitor)
        {
            context.IsAsync();

            long last            = 0;
            long currentInterval = 0;

            string[] streams = Enumerable.Range(0, streamsCnt).Select(x =>
                                                                      string.IsNullOrWhiteSpace(streamNamePrefix)
                                        ? Guid.NewGuid().ToString()
                                        : $"{streamNamePrefix}-{x}"
                                                                      ).ToArray();

            context.Log.Information("Writing streams randomly between {first} and {last}",
                                    streams.FirstOrDefault(),
                                    streams.LastOrDefault());

            var start = new TaskCompletionSource();

            stats.StartTime = DateTime.UtcNow;
            var sw2         = new Stopwatch();
            var capacity    = 2000 / clientsCnt;
            var clientTasks = new List <Task>();

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);

                var client = context._grpcTestClient.CreateGrpcClient();
                clientTasks.Add(RunClient(client, count));
            }

            async Task RunClient(EventStoreClient client, long count)
            {
                var         rnd     = new Random();
                List <Task> pending = new List <Task>(capacity);
                await start.Task;

                for (int j = 0; j < count; ++j)
                {
                    var events = new EventData[batchSize];
                    for (int q = 0; q < batchSize; q++)
                    {
                        events[q] = new EventData(Uuid.FromGuid(Guid.NewGuid()),
                                                  "TakeSomeSpaceEvent",
                                                  UTF8NoBom.GetBytes(
                                                      "{ \"DATA\" : \"" + new string('*', size) + "\"}"),
                                                  UTF8NoBom.GetBytes(
                                                      "{ \"METADATA\" : \"" + new string('$', 100) + "\"}"));
                    }

                    var corrid = Guid.NewGuid();
                    monitor.StartOperation(corrid);

                    pending.Add(client.AppendToStreamAsync(streams[rnd.Next(streamsCnt)], StreamState.Any, events)
                                .ContinueWith(t => {
                        if (t.IsCompletedSuccessfully)
                        {
                            Interlocked.Increment(ref stats.Succ);
                        }
                        else
                        {
                            if (Interlocked.Increment(ref stats.Fail) % 1000 == 0)
                            {
                                Console.Write('#');
                            }
                        }
                        var localAll = Interlocked.Add(ref stats.All, batchSize);
                        if (localAll - currentInterval > interval)
                        {
                            var localInterval = Interlocked.Exchange(ref currentInterval, localAll);
                            stats.Elapsed     = sw2.Elapsed;
                            stats.Rate        = 1000.0 * (localAll - localInterval) / stats.Elapsed.TotalMilliseconds;
                            sw2.Restart();
                            context.Log.Information(
                                "\nDONE TOTAL {writes} WRITES IN {elapsed} ({rate:0.0}/s) [S:{success}, F:{failures} (WEV:{wrongExpectedVersion}, " +
                                "P:{prepareTimeout}, C:{commitTimeout}, F:{forwardTimeout}, D:{streamDeleted})].",
                                localAll, stats.Elapsed, stats.Rate, stats.Succ, stats.Fail,
                                stats.WrongExpVersion, stats.PrepTimeout, stats.CommitTimeout, stats.ForwardTimeout, stats.StreamDeleted);
                            stats.WriteStatsToFile(context.StatsLogger);
                        }

                        monitor.EndOperation(corrid);
                    }));
                    if (pending.Count == capacity)
                    {
                        await Task.WhenAny(pending).ConfigureAwait(false);

                        while (pending.Count > 0 && Task.WhenAny(pending).IsCompleted)
                        {
                            pending.RemoveAll(x => x.IsCompleted);
                            if (stats.Succ - last > 1000)
                            {
                                Console.Write(".");
                                last = stats.Succ;
                            }
                        }
                    }
                }

                if (pending.Count > 0)
                {
                    await Task.WhenAll(pending);
                }
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            start.SetResult();
            await Task.WhenAll(clientTasks);

            sw.Stop();

            context.Log.Information(
                "Completed. Successes: {success}, failures: {failures} (WRONG VERSION: {wrongExpectedVersion}, P: {prepareTimeout}, C: {commitTimeout}, F: {forwardTimeout}, D: {streamDeleted})",
                stats.Succ, stats.Fail,
                stats.WrongExpVersion, stats.PrepTimeout, stats.CommitTimeout, stats.ForwardTimeout, stats.StreamDeleted);
            stats.WriteStatsToFile(context.StatsLogger);

            var reqPerSec = (stats.All + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Information("{requests} requests completed in {elapsed}ms ({rate:0.00} reqs per sec).", stats.All,
                                    sw.ElapsedMilliseconds, reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", stats.Succ), PerfUtils.Col("failures", stats.Fail)));

            var failuresRate = (int)(100 * stats.Fail / (stats.Fail + stats.Succ));

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), failuresRate);
            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-c{1}-r{2}-st{3}-s{4}-reqPerSec", Keyword, clientsCnt, requestsCnt, streamsCnt, size),
                (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-c{1}-r{2}-st{3}-s{4}-failureSuccessRate", Keyword, clientsCnt, requestsCnt,
                              streamsCnt, size), failuresRate);
            monitor.GetMeasurementDetails();
            if (Interlocked.Read(ref stats.Succ) != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
        private void Flood(CommandProcessorContext context,
                           string eventStreamId,
                           int clientsCnt,
                           int minPerSecond,
                           int maxPerSecond,
                           int runTimeMinutes,
                           int dataSize)
        {
            context.IsAsync();

            var threads   = new List <Thread>();
            var doneEvent = new ManualResetEvent(false);

            var succ = 0;
            var fail = 0;

            var requestsCnt = 0;

            int sent     = 0;
            int received = 0;

            var watchLockRoot = new object();
            var sw            = Stopwatch.StartNew();

            for (int i = 0; i < clientsCnt; i++)
            {
                threads.Add(new Thread(() =>
                {
                    var esId = eventStreamId ?? "Stream-" + Thread.CurrentThread.ManagedThreadId % 3;

                    var client = new HttpAsyncClient();

                    Action <HttpResponse> succHandler = response =>
                    {
                        if (response.HttpStatusCode == HttpStatusCode.Created)
                        {
                            var succDone = Interlocked.Increment(ref succ);
                            if (succDone % maxPerSecond == 0)
                            {
                                Console.Write(".");
                            }
                        }
                        else
                        {
                            if (Interlocked.Increment(ref fail) % 10 == 0)
                            {
                                context.Log.Info("ANOTHER 10th WRITE FAILED. [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);
                            }
                        }

                        Interlocked.Increment(ref requestsCnt);
                        Interlocked.Increment(ref received);
                    };

                    var sentCount = 0;
                    var sleepTime = 0;

                    var dataSizeCoefficient = 1;
                    var currentMinute       = -1;

                    while (true)
                    {
                        TimeSpan elapsed;
                        lock (watchLockRoot)
                            elapsed = sw.Elapsed;

                        if (elapsed.TotalMinutes > runTimeMinutes)
                        {
                            doneEvent.Set();
                            break;
                        }

                        if (sentCount == 0)
                        {
                            int elapsedMinutesInt = (int)elapsed.TotalMinutes;

                            lock (_randomLockRoot)
                            {
                                sentCount = minPerSecond == maxPerSecond
                                            ? maxPerSecond : _random.Next(minPerSecond, maxPerSecond);
                                dataSizeCoefficient = _random.Next(8, 256);
                            }

                            if (currentMinute != elapsedMinutesInt)
                            {
                                currentMinute = elapsedMinutesInt;
                                context.Log.Info("\nElapsed {0} of {1} minutes, sent {2}; next block coef. {3}",
                                                 elapsedMinutesInt,
                                                 runTimeMinutes,
                                                 sent,
                                                 dataSizeCoefficient);
                            }

                            sleepTime = 1000 / sentCount;
                        }

                        var url = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", esId);

                        var dataResultingSize = dataSizeCoefficient * dataSize;
                        var write             = new[] { new HttpClientMessageDto.ClientEventText(Guid.NewGuid(),
                                                                                                 "type",
                                                                                                 "DATA" + dataResultingSize.ToString(" 00000 ") + new string('*', dataResultingSize),
                                                                                                 "METADATA" + new string('$', 100)) };
                        var request = Codec.Xml.To(write);
                        client.Post(url,
                                    request,
                                    Codec.Xml.ContentType,
                                    TimeSpan.FromMilliseconds(10000),
                                    succHandler,
                                    exc =>
                        {
                            Interlocked.Increment(ref fail);
                            Interlocked.Increment(ref requestsCnt);
                            context.Log.ErrorException(exc, "Error during POST.");
                        });

                        Interlocked.Increment(ref sent);

                        Thread.Sleep(sleepTime);
                        sentCount -= 1;

                        while (sent - received > context.Client.Options.WriteWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            doneEvent.WaitOne();

            sw.Stop();

            context.Log.Info("Completed. Successes: {0}, failures: {1}", succ, fail);

            var reqPerSec = (requestsCnt + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail))
                );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-{3}-{4}-reqPerSec",
                                                         Keyword,
                                                         clientsCnt,
                                                         minPerSecond,
                                                         maxPerSecond,
                                                         runTimeMinutes),
                                           (int)reqPerSec);

            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt),
                100 * fail / (fail + succ));

            context.Success();
        }
        private void Flood(CommandProcessorContext context,
                           int clientsCnt,
                           int minPerSecond,
                           int maxPerSecond,
                           int runTimeMinutes)
        {
            context.IsAsync();

            var threads        = new List <Thread>();
            var autoResetEvent = new AutoResetEvent(false);

            var succ = 0;
            var fail = 0;

            var requestsCnt = 0;

            var watchLockRoot = new object();
            var sw            = Stopwatch.StartNew();

            for (int i = 0; i < clientsCnt; i++)
            {
                int sent     = 0;
                int received = 0;

                threads.Add(new Thread(() =>
                {
                    var client = new HttpAsyncClient();

                    Action <HttpResponse> succHandler = response =>
                    {
                        var succDone = Interlocked.Increment(ref succ);
                        if (succDone % maxPerSecond == 0)
                        {
                            Console.Write(".");
                        }

                        Interlocked.Increment(ref requestsCnt);
                        Interlocked.Increment(ref received);
                    };

                    var sentCount = 0;
                    var sleepTime = 0;

                    var currentMinute = -1;

                    while (true)
                    {
                        TimeSpan elapsed;
                        lock (watchLockRoot)
                            elapsed = sw.Elapsed;

                        if (elapsed.TotalMinutes > runTimeMinutes)
                        {
                            autoResetEvent.Set();
                            break;
                        }

                        if (sentCount == 0)
                        {
                            int elapsedMinutesInt = (int)elapsed.TotalMinutes;

                            lock (_randomLockRoot)
                            {
                                sentCount = minPerSecond == maxPerSecond
                                                ? maxPerSecond
                                                : _random.Next(minPerSecond, maxPerSecond);
                            }

                            if (currentMinute != elapsedMinutesInt)
                            {
                                currentMinute = elapsedMinutesInt;
                                context.Log.Info(Environment.NewLine + "Elapsed {0} of {1} minutes, sent {2}",
                                                 elapsedMinutesInt,
                                                 runTimeMinutes,
                                                 sent);
                            }

                            sleepTime = 1000 / sentCount;
                        }

                        var url = context.Client.HttpEndpoint.ToHttpUrl("/ping");

                        client.Get(url,
                                   succHandler,
                                   exc => context.Log.ErrorException(exc, "Error during GET."));

                        Interlocked.Increment(ref sent);

                        Thread.Sleep(sleepTime);
                        sentCount -= 1;

                        while (sent - received > context.Client.Options.PingWindow)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();

            sw.Stop();

            context.Log.Info("Completed. Successes: {0}, failures: {1}", succ, fail);

            var reqPerSec = (requestsCnt + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail))
                );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt),
                (int)((fail / (succ + 0.0)) * 100));

            context.Success();
        }
Example #12
0
        private void WriteFlood(CommandProcessorContext context, int clientsCnt, long requestsCnt, int streamsCnt, int size)
        {
            context.IsAsync();

            var doneEvent = new ManualResetEventSlim(false);
            var clients   = new List <TcpTypedConnection <byte[]> >();
            var threads   = new List <Thread>();

            long succ            = 0;
            long fail            = 0;
            long prepTimeout     = 0;
            long commitTimeout   = 0;
            long forwardTimeout  = 0;
            long wrongExpVersion = 0;
            long streamDeleted   = 0;
            long all             = 0;

            var streams = Enumerable.Range(0, streamsCnt).Select(x => Guid.NewGuid().ToString()).ToArray();
            //var streams = Enumerable.Range(0, streamsCnt).Select(x => string.Format("stream-{0}", x)).ToArray();
            var sw2 = new Stopwatch();

            for (int i = 0; i < clientsCnt; i++)
            {
                var  count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long sent     = 0;
                long received = 0;
                var  rnd      = new Random();
                var  client   = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize <TcpClientMessageDto.WriteEventsCompleted>();
                    switch (dto.Result)
                    {
                    case TcpClientMessageDto.OperationResult.Success:
                        if (Interlocked.Increment(ref succ) % 1000 == 0)
                        {
                            Console.Write('.');
                        }
                        break;

                    case TcpClientMessageDto.OperationResult.PrepareTimeout:
                        Interlocked.Increment(ref prepTimeout);
                        break;

                    case TcpClientMessageDto.OperationResult.CommitTimeout:
                        Interlocked.Increment(ref commitTimeout);
                        break;

                    case TcpClientMessageDto.OperationResult.ForwardTimeout:
                        Interlocked.Increment(ref forwardTimeout);
                        break;

                    case TcpClientMessageDto.OperationResult.WrongExpectedVersion:
                        Interlocked.Increment(ref wrongExpVersion);
                        break;

                    case TcpClientMessageDto.OperationResult.StreamDeleted:
                        Interlocked.Increment(ref streamDeleted);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    if (dto.Result != TcpClientMessageDto.OperationResult.Success)
                    {
                        if (Interlocked.Increment(ref fail) % 1000 == 0)
                        {
                            Console.Write('#');
                        }
                    }
                    Interlocked.Increment(ref received);
                    var localAll = Interlocked.Increment(ref all);
                    if (localAll % 100000 == 0)
                    {
                        var elapsed = sw2.Elapsed;
                        sw2.Restart();
                        context.Log.Trace("\nDONE TOTAL {0} WRITES IN {1} ({2:0.0}/s) [S:{3}, F:{4} (WEV:{5}, P:{6}, C:{7}, F:{8}, D:{9})].",
                                          localAll, elapsed, 1000.0 * 100000 / elapsed.TotalMilliseconds,
                                          succ, fail,
                                          wrongExpVersion, prepTimeout, commitTimeout, forwardTimeout, streamDeleted);
                    }
                    if (localAll == requestsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var write = new TcpClientMessageDto.WriteEvents(
                            streams[rnd.Next(streamsCnt)],
                            ExpectedVersion.Any,
                            new[]
                        {
                            new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
                                                             "TakeSomeSpaceEvent",
                                                             1, 0,
                                                             Common.Utils.Helper.UTF8NoBom.GetBytes("{ \"DATA\" : \"" + new string('*', size) + "\"}"),
                                                             Common.Utils.Helper.UTF8NoBom.GetBytes("{ \"METADATA\" : \"" + new string('$', 100) + "\"}"))
                        },
                            false);
                        var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), write.Serialize());
                        client.EnqueueSend(package.AsByteArray());

                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) > context.Client.Options.WriteWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(client => client.Close());

            context.Log.Info("Completed. Successes: {0}, failures: {1} (WRONG VERSION: {2}, P: {3}, C: {4}, F: {5}, D: {6})",
                             succ, fail,
                             wrongExpVersion, prepTimeout, commitTimeout, forwardTimeout, streamDeleted);

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));

            var failuresRate = (int)(100 * fail / (fail + succ));

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), failuresRate);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-reqPerSec", Keyword, clientsCnt, requestsCnt, streamsCnt, size), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-c{1}-r{2}-st{3}-s{4}-failureSuccessRate", Keyword, clientsCnt, requestsCnt, streamsCnt, size), failuresRate);

            if (Interlocked.Read(ref succ) != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
        private void PingFloodWaiting(CommandProcessorContext context, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var  clients     = new List <TcpTypedConnection <byte[]> >();
            var  threads     = new List <Thread>();
            var  doneEvent   = new ManualResetEventSlim(false);
            var  clientsDone = 0;
            long all         = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var autoResetEvent = new AutoResetEvent(false);
                var client         = context.Client.CreateTcpConnection(
                    context,
                    (_, __) =>
                {
                    Interlocked.Increment(ref all);
                    autoResetEvent.Set();
                },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                        client.EnqueueSend(package.AsByteArray());
                        autoResetEvent.WaitOne();
                    }
                    if (Interlocked.Increment(ref clientsDone) == clientsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(x => x.Close());

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)(sw.ElapsedMilliseconds / all));

            if (Interlocked.Read(ref all) == requestsCnt)
            {
                context.Success();
            }
            else
            {
                context.Fail();
            }
        }
Example #14
0
        private void WriteFlood(CommandProcessorContext context, string eventStreamId, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var  threads   = new List <Thread>();
            var  doneEvent = new ManualResetEventSlim(false);
            long all       = 0;
            long succ      = 0;
            long fail      = 0;
            var  sw        = new Stopwatch();
            var  sw2       = new Stopwatch();

            for (int i = 0; i < clientsCnt; i++)
            {
                var  count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long sent     = 0;
                long received = 0;
                threads.Add(new Thread(() =>
                {
                    var esId   = eventStreamId ?? ("es" + Guid.NewGuid());
                    var client = new HttpAsyncClient();

                    Action onReceived = () =>
                    {
                        Interlocked.Increment(ref received);
                        var localAll = Interlocked.Increment(ref all);
                        if (localAll % 10000 == 0)
                        {
                            var elapsed = sw2.Elapsed;
                            sw2.Restart();
                            context.Log.Trace("\nDONE TOTAL {0} WRITES IN {1} ({2:0.0}/s).", localAll, elapsed, 1000.0 * 10000 / elapsed.TotalMilliseconds);
                        }
                        if (localAll == requestsCnt)
                        {
                            doneEvent.Set();
                        }
                    };
                    Action <HttpResponse> onSuccess = response =>
                    {
                        if (response.HttpStatusCode == HttpStatusCode.Created)
                        {
                            if (Interlocked.Increment(ref succ) % 100 == 0)
                            {
                                Console.Write('.');
                            }
                        }
                        else
                        {
                            var localFail = Interlocked.Increment(ref fail);
                            if (localFail % 100 == 0)
                            {
                                Console.Write('#');
                            }
                            if (localFail % 10 == 0)
                            {
                                context.Log.Info("ANOTHER 10th WRITE FAILED. [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);
                            }
                        }
                        onReceived();
                    };
                    Action <Exception> onException = exc =>
                    {
                        context.Log.ErrorException(exc, "Error during POST.");
                        if (Interlocked.Increment(ref fail) % 100 == 0)
                        {
                            Console.Write('#');
                        }
                        onReceived();
                    };

                    for (int j = 0; j < count; ++j)
                    {
                        var url   = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", esId);
                        var write = new[] { new HttpClientMessageDto.ClientEventText(Guid.NewGuid(),
                                                                                     "type",
                                                                                     "DATA" + new string('*', 256),
                                                                                     "METADATA" + new string('$', 100)) };

                        var requestString = Codec.Json.To(write);
                        client.Post(
                            url,
                            requestString,
                            Codec.Json.ContentType,
                            new Dictionary <string, string> {
                        },
                            TimeSpan.FromMilliseconds(10000),
                            onSuccess, onException);

                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) > context.Client.Options.WriteWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                })
                {
                    IsBackground = true
                });
            }

            sw.Start();
            sw2.Start();
            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("Completed. Successes: {0}, failures: {1}", Interlocked.Read(ref succ), Interlocked.Read(ref fail));
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                              PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), (int)(100.0 * fail / (fail + succ)));

            if (Interlocked.Read(ref succ) != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
        private void Flood(CommandProcessorContext context,
                           string eventStreamId,
                           int clientsCnt,
                           int minPerSecond,
                           int maxPerSecond,
                           int runTimeMinutes)
        {
            context.IsAsync();

            var clients   = new List <TcpTypedConnection <byte[]> >();
            var threads   = new List <Thread>();
            var doneEvent = new ManualResetEvent(false);
            var done      = false;

            var succ = 0;
            var fail = 0;

            var requestsCnt = 0;

            int sent     = 0;
            int received = 0;

            var watchLockRoot = new object();
            var sw            = Stopwatch.StartNew();

            for (int i = 0; i < clientsCnt; i++)
            {
                var esId = eventStreamId ?? "Stream-" + Thread.CurrentThread.ManagedThreadId % 3;

                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) => {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize <TcpClientMessageDto.WriteEventsCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        var succDone = Interlocked.Increment(ref succ);
                        if (succDone % maxPerSecond == 0)
                        {
                            Console.Write(".");
                        }

                        Interlocked.Increment(ref requestsCnt);
                    }
                    else
                    {
                        Interlocked.Increment(ref fail);
                    }

                    Interlocked.Increment(ref received);
                },
                    connectionClosed: (conn, err) => {
                    if (!done)
                    {
                        context.Fail(reason: "Socket was closed, but not all requests were completed.");
                    }
                    else
                    {
                        context.Success();
                    }
                });
                clients.Add(client);

                threads.Add(new Thread(() => {
                    var sentCount = 0;
                    var sleepTime = 0;

                    var dataSizeCoefficient = 1;
                    var currentMinute       = -1;

                    while (true)
                    {
                        TimeSpan elapsed;
                        lock (watchLockRoot)
                            elapsed = sw.Elapsed;

                        if (elapsed.TotalMinutes > runTimeMinutes)
                        {
                            done = true;
                            doneEvent.Set();
                            break;
                        }

                        if (sentCount == 0)
                        {
                            int elapsedMinutesInt = (int)elapsed.TotalMinutes;
                            lock (_randomLockRoot) {
                                sentCount = minPerSecond == maxPerSecond
                                                                        ? maxPerSecond
                                                                        : _random.Next(minPerSecond, maxPerSecond);
                                dataSizeCoefficient = _random.Next(8, 256);
                            }

                            if (currentMinute != elapsedMinutesInt)
                            {
                                currentMinute = elapsedMinutesInt;
                                context.Log.Info(
                                    "\nElapsed {elapsed} of {runTime} minutes, sent {sent}; next block coef. {dataSizeCoefficient}",
                                    elapsedMinutesInt,
                                    runTimeMinutes,
                                    sent,
                                    dataSizeCoefficient);
                            }

                            sleepTime = 1000 / sentCount;
                        }

                        var dataSize = dataSizeCoefficient * 8;
                        var write    = new TcpClientMessageDto.WriteEvents(
                            esId,
                            ExpectedVersion.Any,
                            new[] {
                            new TcpClientMessageDto.NewEvent(
                                Guid.NewGuid().ToByteArray(),
                                "TakeSomeSpaceEvent",
                                0, 0,
                                Helper.UTF8NoBom.GetBytes(
                                    "DATA" + dataSize.ToString(" 00000 ") + new string('*', dataSize)),
                                Helper.UTF8NoBom.GetBytes("METADATA" + new string('$', 100)))
                        },
                            false);
                        var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), write.Serialize());
                        client.EnqueueSend(package.AsByteArray());

                        Interlocked.Increment(ref sent);

                        Thread.Sleep(sleepTime);
                        sentCount -= 1;

                        while (sent - received > context.Client.Options.WriteWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            doneEvent.WaitOne();
            sw.Stop();

            foreach (var client in clients)
            {
                client.Close();
            }

            context.Log.Info("Completed. Successes: {success}, failures: {failures}", succ, fail);
            var reqPerSec = (requestsCnt + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{requests} requests completed in {elapsed}ms ({rate:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail))
                );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt),
                100 * fail / (fail + succ));

            context.Success();
        }
        private void WriteFlood(CommandProcessorContext context, int writeCnt, int clientsCnt, int requestsCnt)
        {
            context.IsAsync();

            const string data = "test-data";

            var clients        = new ConcurrentBag <TcpTypedConnection <byte[]> >();
            var threads        = new List <Thread>();
            var autoResetEvent = new AutoResetEvent(false);

            var succ = 0;
            var fail = 0;
            var all  = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);

                var autoEvent     = new AutoResetEvent(false);
                var eventStreamId = "es" + Guid.NewGuid();

                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize <ClientMessageDto.WriteEventsCompleted>();
                    if (dto.ErrorCode == (int)OperationErrorCode.Success)
                    {
                        if (Interlocked.Increment(ref succ) % 1000 == 0)
                        {
                            Console.Write(".");
                        }
                    }
                    else
                    {
                        Interlocked.Increment(ref fail);
                    }

                    if (Interlocked.Increment(ref all) == requestsCnt)
                    {
                        autoResetEvent.Set();
                    }
                    autoEvent.Set();
                },
                    connectionClosed: (conn, err) =>
                {
                    if (all < requestsCnt)
                    {
                        context.Fail(null, "Socket was closed, but not all requests were completed.");
                    }
                    else
                    {
                        context.Success();
                    }
                });
                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var writeDto = new ClientMessageDto.WriteEvents(
                            eventStreamId,
                            ExpectedVersion.Any,
                            Enumerable.Range(0, writeCnt).Select(x =>
                                                                 new ClientMessageDto.Event(Guid.NewGuid(),
                                                                                            "type",
                                                                                            Encoding.UTF8.GetBytes(data),
                                                                                            new byte[0])).ToArray());
                        var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), writeDto.Serialize());
                        client.EnqueueSend(package.AsByteArray());
                        autoEvent.WaitOne();
                    }
                }));
            }

            var sw = Stopwatch.StartNew();

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();
            sw.Stop();

            foreach (var client in clients)
            {
                client.Close();
            }

            context.Log.Info("Completed. Successes: {0}, failures: {1}", succ, fail);

            var reqPerSec = (requestsCnt + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             all,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt),
                100 * fail / (fail + succ));

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword),
                                           (int)(sw.ElapsedMilliseconds / requestsCnt));

            context.Success();
        }
        private void WriteFlood(CommandProcessorContext context, int writeCnt, int clientsCnt, long requestsCnt)
        {
            const string data = "test-data";

            context.IsAsync();

            var  clients   = new List <TcpTypedConnection <byte[]> >();
            var  threads   = new List <Thread>();
            var  doneEvent = new ManualResetEventSlim(false);
            long succ      = 0;
            long fail      = 0;
            long all       = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count          = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                var localDoneEvent = new AutoResetEvent(false);
                var eventStreamId  = "es" + Guid.NewGuid();
                var client         = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize <TcpClientMessageDto.WriteEventsCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        if (Interlocked.Increment(ref succ) % 1000 == 0)
                        {
                            Console.Write(".");
                        }
                    }
                    else
                    {
                        if (Interlocked.Increment(ref fail) % 1000 == 0)
                        {
                            Console.Write("#");
                        }
                    }

                    if (Interlocked.Increment(ref all) == requestsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                    localDoneEvent.Set();
                },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var writeDto = new TcpClientMessageDto.WriteEvents(
                            eventStreamId,
                            ExpectedVersion.Any,
                            Enumerable.Range(0, writeCnt).Select(x =>
                                                                 new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
                                                                                                  "type",
                                                                                                  0, 0,
                                                                                                  Common.Utils.Helper.UTF8NoBom.GetBytes(data),
                                                                                                  new byte[0])).ToArray(),
                            false);
                        var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), writeDto.Serialize());
                        client.EnqueueSend(package.AsByteArray());
                        localDoneEvent.WaitOne();
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(client => client.Close());

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("Completed. Successes: {success}, failures: {failures}", succ, fail);
            context.Log.Info("{requests} requests completed in {elapsed}ms ({rate:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);

            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                              PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), (int)(100.0 * fail / (fail + succ)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)Math.Round(sw.Elapsed.TotalMilliseconds / requestsCnt));

            if (succ != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
Example #18
0
        private void WriteFlood(CommandProcessorContext context, int clientsCnt, int requestsCnt)
        {
            context.IsAsync();

            var threads   = new List <Thread>();
            var doneEvent = new ManualResetEventSlim(false);
            var succ      = 0;
            var fail      = 0;
            var all       = 0;
            var sw        = Stopwatch.StartNew();

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                threads.Add(new Thread(() =>
                {
                    var autoEvent     = new AutoResetEvent(false);
                    var eventStreamId = "es" + Guid.NewGuid();
                    var client        = new HttpAsyncClient();
                    var url           = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", eventStreamId);
                    Action <HttpResponse> succHandler = response =>
                    {
                        if (response.HttpStatusCode == HttpStatusCode.Created)
                        {
                            if (Interlocked.Increment(ref succ) % 1000 == 0)
                            {
                                Console.Write(".");
                            }
                        }
                        else
                        {
                            if (Interlocked.Increment(ref fail) % 10 == 0)
                            {
                                context.Log.Info("ANOTHER 10th WRITE FAILED. [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);
                            }
                        }
                        if (Interlocked.Increment(ref all) == requestsCnt)
                        {
                            doneEvent.Set();
                        }
                        autoEvent.Set();
                    };

                    for (int j = 0; j < count; ++j)
                    {
                        var write = new[] { new HttpClientMessageDto.ClientEventText(Guid.NewGuid(),
                                                                                     "type",
                                                                                     "DATA" + new string('*', 256),
                                                                                     "METADATA" + new string('$', 100)) };
                        var request = Codec.Xml.To(write);
                        client.Post(url,
                                    request,
                                    Codec.Xml.ContentType,
                                    TimeSpan.FromMilliseconds(10000),
                                    succHandler,
                                    exc =>
                        {
                            context.Log.ErrorException(exc, "Error during POST.");
                            Interlocked.Increment(ref fail);
                            if (Interlocked.Increment(ref all) == requestsCnt)
                            {
                                doneEvent.Set();
                            }
                            autoEvent.Set();
                        });
                        autoEvent.WaitOne();
                    }
                })
                {
                    IsBackground = true
                });
            }

            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("Completed. Successes: {0}, failures: {1}", succ, fail);
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).", all, sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                              PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), (int)(100.0 * fail / (fail + succ)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)Math.Round(sw.Elapsed.TotalMilliseconds / requestsCnt));

            if (succ != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }
        private void PingFlood(CommandProcessorContext context, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var  doneEvent = new ManualResetEventSlim(false);
            var  clients   = new List <TcpTypedConnection <byte[]> >();
            var  threads   = new List <Thread>();
            long all       = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var  count    = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                long received = 0;
                long sent     = 0;
                var  client   = context._tcpTestClient.CreateTcpConnection(
                    context,
                    (conn, msg) => {
                    Interlocked.Increment(ref received);
                    var pongs = Interlocked.Increment(ref all);
                    if (pongs % 10000 == 0)
                    {
                        Console.Write('.');
                    }
                    if (pongs == requestsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                threads.Add(new Thread(() => {
                    for (int j = 0; j < count; ++j)
                    {
                        var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), Payload);
                        client.EnqueueSend(package.AsByteArray());

                        var localSent = Interlocked.Increment(ref sent);
                        while (localSent - Interlocked.Read(ref received) >
                               context._tcpTestClient.Options.PingWindow / clientsCnt)
                        {
                            Thread.Sleep(1);
                        }
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(client => client.Close());

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Information("{requests} requests completed in {elapsed}ms ({rate:0.00} reqs per sec).", all,
                                    sw.ElapsedMilliseconds, reqPerSec);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            if (Interlocked.Read(ref all) == requestsCnt)
            {
                context.Success();
            }
            else
            {
                context.Fail();
            }
        }
        private void WriteFlood(CommandProcessorContext context, string eventStreamId, int clientsCnt, int requestsCnt)
        {
            context.IsAsync();

            var threads        = new List <Thread>();
            var autoResetEvent = new AutoResetEvent(false);

            var succ = 0;
            var fail = 0;
            var all  = 0;

            var sw = Stopwatch.StartNew();

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);

                int sent     = 0;
                int received = 0;

                threads.Add(new Thread(() =>
                {
                    var esId = eventStreamId ?? "es" + Guid.NewGuid();

                    var client = new HttpAsyncClient();

                    Action <HttpResponse> succHandler = response =>
                    {
                        if (response.HttpStatusCode == HttpStatusCode.Created)
                        {
                            if (Interlocked.Increment(ref succ) % 100 == 0)
                            {
                                Console.Write(".");
                            }
                        }
                        else
                        {
                            if (Interlocked.Increment(ref fail) % 10 == 0)
                            {
                                context.Log.Info("ANOTHER 10th WRITE FAILED. [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);
                            }
                        }

                        Interlocked.Increment(ref received);
                        if (Interlocked.Increment(ref all) == requestsCnt)
                        {
                            autoResetEvent.Set();
                        }
                    };

                    for (int j = 0; j < count; ++j)
                    {
                        var url   = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", esId);
                        var write = new ClientMessageDto.WriteEventText(
                            Guid.Empty,
                            ExpectedVersion.Any,
                            new[] {
                            new ClientMessageDto.EventText(Guid.NewGuid(),
                                                           "type",
                                                           "DATA" + new string('*', 256),
                                                           "METADATA" + new string('$', 100))
                        });
                        var requestString = Codec.Xml.To(write);
                        client.Post(url, requestString, Codec.Xml.ContentType, succHandler, exc =>
                        {
                            context.Log.ErrorException(exc, "Error during POST.");
                            Interlocked.Increment(ref fail);
                            if (Interlocked.Increment(ref all) == requestsCnt)
                            {
                                autoResetEvent.Set();
                            }
                        });

                        Interlocked.Increment(ref sent);

                        while (sent - received > context.Client.Options.WriteWindow)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();
            sw.Stop();

            context.Log.Info("Completed. Successes: {0}, failures: {1}", succ, fail);
            var reqPerSec = (requestsCnt + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail))
                );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            PerfUtils.LogTeamCityGraphData(
                string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt),
                100 * fail / (fail + succ));

            context.Success();
        }
Example #21
0
        private void ReadFlood(CommandProcessorContext context, string eventStreamId, int clientsCnt, long requestsCnt)
        {
            context.IsAsync();

            var clients        = new List <TcpTypedConnection <byte[]> >();
            var threads        = new List <Thread>();
            var autoResetEvent = new AutoResetEvent(false);
            var sw2            = new Stopwatch();

            long all = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);

                int sent     = 0;
                int received = 0;

                var client = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) =>
                {
                    Interlocked.Increment(ref received);

                    var localAll = Interlocked.Increment(ref all);
                    if (localAll % 1000 == 0)
                    {
                        Console.Write(".");
                    }
                    if (localAll % 100000 == 0)
                    {
                        var elapsed = sw2.Elapsed;
                        sw2.Restart();
                        context.Log.Trace("\nDONE TOTAL {0} READS IN {1} ({2:0.0}/s).",
                                          localAll,
                                          elapsed,
                                          1000.0 * 100000 / elapsed.TotalMilliseconds);
                    }
                    if (localAll == requestsCnt)
                    {
                        autoResetEvent.Set();
                    }
                },
                    connectionClosed: (conn, err) =>
                {
                    if (all < requestsCnt)
                    {
                        context.Fail(null, "Socket was closed, but not all requests were completed.");
                    }
                    else
                    {
                        context.Success();
                    }
                });

                client.ConnectionClosed += (_, __) => context.Log.Debug("READS sent: {0}, received: {1}", sent, received);
                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var read    = new ClientMessageDto.ReadEvent(Guid.NewGuid(), eventStreamId, 0);
                        var package = new TcpPackage(TcpCommand.ReadEvent, read.Serialize());
                        client.EnqueueSend(package.AsByteArray());

                        Interlocked.Increment(ref sent);
                        while (sent - received > context.Client.Options.ReadWindow)
                        {
                            Thread.Sleep(1);
                        }
                    }
                }));
            }

            var sw = Stopwatch.StartNew();

            sw2.Start();
            foreach (var thread in threads)
            {
                thread.IsBackground = true;
                thread.Start();
            }

            autoResetEvent.WaitOne();
            sw.Stop();

            foreach (var client in clients)
            {
                client.Close();
            }

            context.Log.Info("Completed. READS done: {0}.", all);

            var reqPerSec = (requestsCnt + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec).",
                             requestsCnt,
                             sw.ElapsedMilliseconds,
                             reqPerSec);

            PerfUtils.LogData(
                Keyword,
                PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                              PerfUtils.Col("requestsCnt", requestsCnt),
                              PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                PerfUtils.Row(PerfUtils.Col("readsCnt", all))
                );

            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt),
                                           (int)reqPerSec);

            context.Success();
        }
        private void WriteFlood(CommandProcessorContext context, int clientsCnt, int requestsCnt, int payloadSize)
        {
            context.IsAsync();

            var dataSize     = Math.Max(0, payloadSize - 100);
            var metadataSize = Math.Min(100, payloadSize);

            var clients   = new List <TcpTypedConnection <byte[]> >();
            var threads   = new List <Thread>();
            var doneEvent = new ManualResetEventSlim(false);
            var succ      = 0;
            var fail      = 0;
            var all       = 0;

            for (int i = 0; i < clientsCnt; i++)
            {
                var count         = requestsCnt / clientsCnt + ((i == clientsCnt - 1) ? requestsCnt % clientsCnt : 0);
                var autoEvent     = new AutoResetEvent(false);
                var eventStreamId = "es" + Guid.NewGuid();
                var received      = 0;
                var client        = context.Client.CreateTcpConnection(
                    context,
                    (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    Interlocked.Increment(ref received);
                    var dto = pkg.Data.Deserialize <TcpClientMessageDto.WriteEventsCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        if (Interlocked.Increment(ref succ) % 1000 == 0)
                        {
                            Console.Write(".");
                        }
                    }
                    else
                    {
                        if (Interlocked.Increment(ref fail) % 1000 == 0)
                        {
                            Console.Write("#");
                        }
                    }

                    if (Interlocked.Increment(ref all) == requestsCnt)
                    {
                        context.Success();
                        doneEvent.Set();
                    }
                    autoEvent.Set();
                },
                    connectionClosed: (conn, err) => context.Fail(reason: "Connection was closed prematurely."));
                clients.Add(client);

                threads.Add(new Thread(() =>
                {
                    for (int j = 0; j < count; ++j)
                    {
                        var write = new TcpClientMessageDto.WriteEvents(
                            eventStreamId,
                            ExpectedVersion.Any,
                            new[]
                        {
                            new TcpClientMessageDto.NewEvent(Guid.NewGuid().ToByteArray(),
                                                             "TakeSomeSpaceEvent",
                                                             0, 0,
                                                             Common.Utils.Helper.UTF8NoBom.GetBytes("DATA" + new string('*', dataSize)),
                                                             Common.Utils.Helper.UTF8NoBom.GetBytes("METADATA" + new string('$', metadataSize)))
                        },
                            false);
                        var package = new TcpPackage(TcpCommand.WriteEvents, Guid.NewGuid(), write.Serialize());
                        client.EnqueueSend(package.AsByteArray());
                        autoEvent.WaitOne();
                    }
                })
                {
                    IsBackground = true
                });
            }

            var sw = Stopwatch.StartNew();

            threads.ForEach(thread => thread.Start());
            doneEvent.Wait();
            sw.Stop();
            clients.ForEach(client => client.Close());

            var reqPerSec = (all + 0.0) / sw.ElapsedMilliseconds * 1000;

            context.Log.Info("Completed. Successes: {0}, failures: {1}", succ, fail);
            context.Log.Info("{0} requests completed in {1}ms ({2:0.00} reqs per sec, latency: {3:0.00} ms).",
                             all, sw.ElapsedMilliseconds, reqPerSec, (sw.ElapsedMilliseconds + 0.0) / requestsCnt);
            PerfUtils.LogData(Keyword,
                              PerfUtils.Row(PerfUtils.Col("clientsCnt", clientsCnt),
                                            PerfUtils.Col("requestsCnt", requestsCnt),
                                            PerfUtils.Col("ElapsedMilliseconds", sw.ElapsedMilliseconds)),
                              PerfUtils.Row(PerfUtils.Col("successes", succ), PerfUtils.Col("failures", fail)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-reqPerSec", Keyword, clientsCnt, requestsCnt), (int)reqPerSec);
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-{1}-{2}-failureSuccessRate", Keyword, clientsCnt, requestsCnt), (int)(100.0 * fail / (fail + succ)));
            PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)(sw.ElapsedMilliseconds / requestsCnt));

            if (succ != requestsCnt)
            {
                context.Fail(reason: "There were errors or not all requests completed.");
            }
            else
            {
                context.Success();
            }
        }