当前位置: 首页>>代码示例>>C#>>正文


C# CommandProcessorContext.Fail方法代码示例

本文整理汇总了C#中CommandProcessorContext.Fail方法的典型用法代码示例。如果您正苦于以下问题:C# CommandProcessorContext.Fail方法的具体用法?C# CommandProcessorContext.Fail怎么用?C# CommandProcessorContext.Fail使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在CommandProcessorContext的用法示例。


在下文中一共展示了CommandProcessorContext.Fail方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
                    context.Log.Info("[{0}:{1}]: PING...", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.Pong)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }
                    context.Log.Info("[{0}:{1}]: PONG!", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    context.Success();
                    conn.Close();
                },
                connectionClosed: (typedConnection, error) => context.Fail(reason: "Connection was closed prematurely."));
            context.WaitForCompletion();
            return true;
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:27,代码来源:PingProcessor.cs

示例2: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            context.IsAsync();

            var package = new TcpPackage(TcpCommand.Ping, Guid.NewGuid(), null);
            context.Log.Info("[{0}:{1}]: PING...", context.Client.Options.Ip, context.Client.Options.TcpPort);

            var connection = context.Client.CreateTcpConnection(
                context,
                (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.Pong)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }
                    context.Log.Info("[{0}:{1}]: PONG!", context.Client.Options.Ip, context.Client.Options.TcpPort);
                    conn.Close();
                    context.Success();
                },
                null,
                (typedConnection, error) =>
                    {
                        if (error == SocketError.Success)
                            context.Success();
                        else
                            context.Fail();
                    });
            connection.EnqueueSend(package.AsByteArray());
            context.WaitForCompletion();
            return true;
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:32,代码来源:PingProcessor.cs

示例3: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;
                eventStreamId = args[0];
                if (args.Length == 2)
                    expectedVersion = args[1].Trim().ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
            }

            context.IsAsync();
            var sw = new Stopwatch();
            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}, L{1}]: Trying to delete event stream '{2}'...", conn.RemoteEndPoint, conn.LocalEndPoint, eventStreamId);
                    var corrid = Guid.NewGuid();
                    var deleteDto = new TcpClientMessageDto.DeleteStream(eventStreamId, expectedVersion, false, true);
                    var package = new TcpPackage(TcpCommand.DeleteStream, corrid, deleteDto.Serialize()).AsByteArray();
                    sw.Start();
                    conn.EnqueueSend(package);
                },
                handlePackage: (conn, pkg) =>
                {
                    sw.Stop();
                    context.Log.Info("Delete request took: {0}.", sw.Elapsed);

                    if (pkg.Command != TcpCommand.DeleteStreamCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    var dto = pkg.Data.Deserialize<TcpClientMessageDto.DeleteStreamCompleted>();
                    if (dto.Result == TcpClientMessageDto.OperationResult.Success)
                    {
                        context.Log.Info("DELETED event stream {0}.", eventStreamId);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)Math.Round(sw.Elapsed.TotalMilliseconds));
                        context.Success();
                    }
                    else
                    {
                        context.Log.Info("DELETION FAILED for event stream {0}: {1} ({2}).", eventStreamId, dto.Message, dto.Result);
                        context.Fail();
                    }
                    conn.Close();
                },
                connectionClosed:(connection, error) => context.Fail(reason: "Connection was closed prematurely."));

            context.WaitForCompletion();
            return true;
        }
开发者ID:czcz1024,项目名称:EventStore,代码行数:57,代码来源:DeleteProcessor.cs

示例4: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var expectedVersion = ExpectedVersion.Any;
            string metadata = "{'user' : 'test'}";
            var requireMaster = false;
            var data = "{'a' : 3 }";
            if (args.Length > 0)
            {
                if (args.Length != 5)
                    return false;
                eventStreamId = args[0];
                expectedVersion = args[1].ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[1]);
                data = args[2];
                metadata = args[3];
                requireMaster = bool.Parse(args[4]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var url = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}", eventStreamId);
            context.Log.Info("Writing to {0}...", url);
            var msg = "[{'eventType': 'fooevent', 'eventId' : '" + Guid.NewGuid() + "'" + ",'data' : " + data + ", 'metadata' : " + metadata + "}]";

            var sw = Stopwatch.StartNew();
            client.Post(
                url,
                msg,
                Codec.Json.ContentType,
                new Dictionary<string, string>
                {
                        {SystemHeaders.ExpectedVersion, expectedVersion.ToString()},
                        {SystemHeaders.RequireMaster, requireMaster ? "True" : "False"}
                },
                TimeSpan.FromMilliseconds(10000),
                response =>
                {
                    sw.Stop();
                    if (response.HttpStatusCode == HttpStatusCode.Created)
                        context.Log.Info("Successfully written");
                    else
                    {
                        context.Log.Info("Error while writing: [{0}] - [{1}]", response.HttpStatusCode, response.StatusDescription);
                        context.Log.Info("Response:\n{0}\n\n{1}\n",
                                         string.Join("\n", response.Headers.AllKeys.Select(x => string.Format("{0,-20}: {1}", x, response.Headers[x]))),
                                         response.Body);
                    }

                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    context.Success();
                },
                e =>
                {
                    context.Log.ErrorException(e, "Error during POST");
                    context.Fail(e, "Error during POST.");
                });

            return true;
        }
开发者ID:kijanawoodard,项目名称:EventStore,代码行数:60,代码来源:WriteHttpProcessor.cs

示例5: PingFloodWaiting

        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) Math.Round(sw.Elapsed.TotalMilliseconds/all));

            if (Interlocked.Read(ref all) == requestsCnt)
                context.Success();
            else
                context.Fail();
        }
开发者ID:czcz1024,项目名称:EventStore,代码行数:59,代码来源:PingFloodWaitingProcessor.cs

示例6: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var eventNumber = 0;
            var resolveLinkTos = false;
            var requireMaster = false;

            if (args.Length > 0)
            {
                if (args.Length > 3)
                    return false;
                eventStreamId = args[0];
                if (args.Length >= 2)
                    eventNumber = int.Parse(args[1]);
                if (args.Length >= 3)
                    requireMaster = bool.Parse(args[2]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var readUrl = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}/{1}?format=json", eventStreamId,
                                                                eventNumber == -1 ? "head" : eventNumber.ToString());

            context.Log.Info("[{0}]: Reading...", context.Client.HttpEndpoint);

            var sw = Stopwatch.StartNew();
            client.Get(readUrl,
                       new Dictionary<string, string>
                       {
                            {SystemHeaders.ResolveLinkTos, resolveLinkTos ? "True" : "False"},
                            {SystemHeaders.RequireMaster, requireMaster ? "True" : "False"}
                       },
                       TimeSpan.FromMilliseconds(10000),
                       response =>
                       {
                           sw.Stop();
                           context.Log.Info("[{0} ({1})]: READ events from <{2}>.",
                                            response.HttpStatusCode, response.StatusDescription, eventStreamId);
                           context.Log.Info("Response:\n{0}\n\n{1}\n",
                                            string.Join("\n", response.Headers.AllKeys.Select(x => string.Format("{0,-20}: {1}", x, response.Headers[x]))),
                                            response.Body);
                           context.Log.Info("Read request took: {0}.", sw.Elapsed);
                           context.Success();
                       },
                       e => context.Fail(e, string.Format("READ events from <{0}>: FAILED", eventStreamId)));

            return true;
        }
开发者ID:kijanawoodard,项目名称:EventStore,代码行数:49,代码来源:ReadHttpProcessor.cs

示例7: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var package = new TcpPackage(TcpCommand.ScavengeDatabase, Guid.NewGuid(), null);
            context.Log.Info("Sending SCAVENGE request...");

            var connection = context.Client.CreateTcpConnection(
                context,
                (conn, pkg) => { },
                null,
                (typedConnection, error) =>
                {
                    if (error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });
            connection.EnqueueSend(package.AsByteArray());
            connection.Close("OK");
            return true;
        }
开发者ID:thinkbeforecoding,项目名称:EventStore,代码行数:20,代码来源:ScavengeProcessor.cs

示例8: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var version = 0;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;

                eventStreamId = args[0];

                if (args.Length == 2)
                    version = int.Parse(args[1]);
            }

            context.IsAsync();

            var client = new HttpAsyncClient();
            var readUrl = context.Client.HttpEndpoint.ToHttpUrl("/streams/{0}/event/{1}", eventStreamId, version);

            context.Log.Info("[{0}]: Reading...", context.Client.HttpEndpoint);

            var sw = Stopwatch.StartNew();
            client.Get(readUrl,
                       response =>
                       {
                           sw.Stop();
                           context.Log.Info("READ events from <{0}>: {1}", eventStreamId, response.Body);
                           context.Log.Info("Read request took: {0}.", sw.Elapsed);
                           context.Success();
                       },
                       e => context.Fail(e, string.Format("READ events from <{0}>: FAILED", eventStreamId)));

            return true;
        }
开发者ID:vishal-h,项目名称:EventStore-1,代码行数:36,代码来源:ReadHttpProcessor.cs

示例9: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            const string data = "test-data";
            var writeCount = 10;
            var expectedVersion = ExpectedVersion.Any;

            if (args.Length > 0)
            {
                if (args.Length > 3)
                    return false;
                writeCount = int.Parse(args[0]);
                if (args.Length >= 2)
                    eventStreamId = args[1];
                if (args.Length >= 3)
                    expectedVersion = args[2].Trim().ToUpper() == "ANY" ? ExpectedVersion.Any : int.Parse(args[2].Trim());
            }

            context.IsAsync();

            var writeDto = new ClientMessageDto.WriteEvents(
                Guid.Empty,
                eventStreamId,
                expectedVersion,
                Enumerable.Range(0, writeCount).Select(x =>
                                                       new ClientMessageDto.Event(Guid.NewGuid(),
                                                                                  "type",
                                                                                  Encoding.UTF8.GetBytes(data),
                                                                                  new byte[0])).ToArray());

            var package = new TcpPackage(TcpCommand.WriteEvents, writeDto.Serialize());

            var sw = new Stopwatch();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}]: Writing...", conn.EffectiveEndPoint);
                    sw.Start();
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.WriteEventsCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    sw.Stop();

                    var dto = pkg.Data.Deserialize<ClientMessageDto.WriteEventsCompleted>();
                    if (dto.ErrorCode == (int)OperationErrorCode.Success)
                    {
                        context.Log.Info("Successfully written {0} events. CorrelationId: {1}.",
                                         writeCount,
                                         dto.CorrelationId);
                        PerfUtils.LogTeamCityGraphData(string.Format("{0}-latency-ms", Keyword), (int)sw.ElapsedMilliseconds);
                    }
                    else
                    {
                        context.Log.Info("Error while writing: {0}. CorrelationId: {1}.", dto.Error, dto.CorrelationId);
                    }
                    context.Log.Info("Write request took: {0}.", sw.Elapsed);
                    
                    conn.Close();
                    context.Success();
                },
                connectionClosed:(connection, error) =>
                    {
                        if(error == SocketError.Success)
                            context.Success();
                        else
                            context.Fail();
                    });

            context.WaitForCompletion();
            return true;
        }
开发者ID:vishal-h,项目名称:EventStore-1,代码行数:80,代码来源:MultiWriteProcessor.cs

示例10: PingFlood

        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.Client.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.Client.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.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 all) == requestsCnt)
                context.Success();
            else
                context.Fail();
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:65,代码来源:PingFloodProcessor.cs

示例11: Execute


//.........这里部分代码省略.........
                                    eventsPerStream, 
                                    streamDeleteStep, 
                                    TimeSpan.FromMinutes(executionPeriodMinutes),
                                    dbParentPath,
                                    customNode), 
                new ProjectionsKillScenario(directTcpSender,
                                            maxConcurrentRequests,
                                            connections,
                                            streams,
                                            eventsPerStream,
                                            streamDeleteStep, 
                                            dbParentPath,
                                            customNode),
                new ProjForeachForcedCommonNameScenario(directTcpSender,
                                            maxConcurrentRequests,
                                            connections,
                                            streams,
                                            eventsPerStream,
                                            streamDeleteStep,
                                            TimeSpan.FromMinutes(executionPeriodMinutes),
                                            dbParentPath,
                                            customNode),
                new ProjForeachForcedCommonNameNoRestartScenario (directTcpSender, 
                                            maxConcurrentRequests, 
                                            connections, 
                                            streams, 
                                            eventsPerStream, 
                                            streamDeleteStep, 
                                            TimeSpan.FromMinutes(executionPeriodMinutes),
                                            dbParentPath,
                                            customNode), 
                new LoopingProjTranWriteScenario(directTcpSender, 
                                            maxConcurrentRequests, 
                                            connections, 
                                            streams, 
                                            eventsPerStream, 
                                            streamDeleteStep,
                                            TimeSpan.FromMinutes(executionPeriodMinutes),
                                            dbParentPath,
                                            customNode), 
                new LoopingProjectionKillScenario(directTcpSender, 
                                                  maxConcurrentRequests, 
                                                  connections, 
                                                  streams, 
                                                  eventsPerStream, 
                                                  streamDeleteStep, 
                                                  TimeSpan.FromMinutes(executionPeriodMinutes),
                                                  dbParentPath,
                                                  customNode), 
                new MassProjectionsScenario(directTcpSender, 
                                            maxConcurrentRequests, 
                                            connections, 
                                            streams, 
                                            eventsPerStream, 
                                            streamDeleteStep, 
                                            dbParentPath,
                                            customNode),
                new ProjectionWrongTagCheck(directTcpSender, 
                                            maxConcurrentRequests, 
                                            connections, 
                                            streams, 
                                            eventsPerStream, 
                                            streamDeleteStep, 
                                            TimeSpan.FromMinutes(executionPeriodMinutes),
                                            dbParentPath,
                                            customNode), 
                };

            Log.Info("Found scenarios {0} total :\n{1}.", allScenarios.Length, allScenarios.Aggregate(new StringBuilder(),
                                                                                                       (sb, s) => sb.AppendFormat("{0}, ", s.GetType().Name)));
            var scenarios = allScenarios.Where(x => scenarioName == AllScenariosFlag
                                                    || x.GetType().Name.Equals(scenarioName, StringComparison.InvariantCultureIgnoreCase))
                                        .ToArray();

            Log.Info("Running test scenarios ({0} total)...", scenarios.Length);

            foreach (var scenario in scenarios)
            {
                using (scenario)
                {
                    try
                    {
                        Log.Info("Run scenario {0}", scenario.GetType().Name);
                        scenario.Run();
                        scenario.Clean();
                        Log.Info("Scenario run successfully");
                    }
                    catch (Exception e)
                    {
                        context.Fail(e);
                    }
                }
            }
            Log.Info("Finished running test scenarios");

            if (context.ExitCode == 0)
                context.Success();

            return true;
        }
开发者ID:danieldeb,项目名称:EventStore,代码行数:101,代码来源:RunTestScenariosProcessor.cs

示例12: WriteFlood

        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)(sw.ElapsedMilliseconds / requestsCnt));

            if (succ != requestsCnt)
                context.Fail(reason: "There were errors or not all requests completed.");
            else
                context.Success();
        }
开发者ID:jjvdangelo,项目名称:EventStore,代码行数:81,代码来源:WriteFloodWaitingHttpProcessor.cs

示例13: WriteFlood

        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
//.........这里部分代码省略.........
开发者ID:danieldeb,项目名称:EventStore,代码行数:101,代码来源:WriteFloodClientApiProcessor.cs

示例14: Flood

        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 {0} of {1} minutes, sent {2}; next block coef. {3}",
                                                 elapsedMinutesInt,
                                                 runTimeMinutes,
                                                 sent,
                                                 dataSizeCoefficient);
//.........这里部分代码省略.........
开发者ID:danieldeb,项目名称:EventStore,代码行数:101,代码来源:WriteLongTermProcessor.cs

示例15: Execute

        public bool Execute(CommandProcessorContext context, string[] args)
        {
            var eventStreamId = "test-stream";
            var fromNumber = 0;

            if (args.Length > 0)
            {
                if (args.Length > 2)
                    return false;

                eventStreamId = args[0];

                if (args.Length == 2)
                    fromNumber = int.Parse(args[1]);
            }

            context.IsAsync();

            var readDto = new ClientMessageDto.ReadEvent(Guid.NewGuid(), eventStreamId, fromNumber);
            var package = new TcpPackage(TcpCommand.ReadEvent, readDto.Serialize());

            var sw = new Stopwatch();

            context.Client.CreateTcpConnection(
                context,
                connectionEstablished: conn =>
                {
                    context.Log.Info("[{0}]: Reading...", conn.EffectiveEndPoint);
                    sw.Start();
                    conn.EnqueueSend(package.AsByteArray());
                },
                handlePackage: (conn, pkg) =>
                {
                    if (pkg.Command != TcpCommand.ReadEventCompleted)
                    {
                        context.Fail(reason: string.Format("Unexpected TCP package: {0}.", pkg.Command));
                        return;
                    }

                    sw.Stop();

                    var dto = pkg.Data.Deserialize<ClientMessageDto.ReadEventCompleted>();

                    context.Log.Info("READ events from <{0}>:\n\n"
                                     + "\tCorrelationId: {1}\n"
                                     + "\tEventStreamId: {2}\n"
                                     + "\tEventNumber:   {3}\n"
                                     + "\tReadResult:    {4}\n"
                                     + "\tEventType:     {5}\n"
                                     + "\tData:          {6}\n"
                                     + "\tMetadata:      {7}\n",
                                     eventStreamId,
                                     dto.CorrelationId,
                                     dto.EventStreamId,
                                     dto.EventNumber,
                                     (SingleReadResult) dto.Result,
                                     dto.EventType,
                                     Encoding.UTF8.GetString(dto.Data ?? new byte[0]),
                                     Encoding.UTF8.GetString(dto.Metadata ?? new byte[0]));

                    context.Log.Info("Read request took: {0}.", sw.Elapsed);

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

                    conn.Close();
                    context.Success();
                },
                connectionClosed: (connection, error) =>
                {
                    if (error == SocketError.Success)
                        context.Success();
                    else
                        context.Fail();
                });

            context.WaitForCompletion();
            return true;
        }
开发者ID:jpierson,项目名称:EventStore,代码行数:78,代码来源:ReadProcessor.cs


注:本文中的CommandProcessorContext.Fail方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。