예제 #1
0
        static string DetectXcodePath()
        {
            using var process           = new Process();
            process.StartInfo.FileName  = "xcode-select";
            process.StartInfo.Arguments = "-p";

            var log    = new MemoryLog();
            var stdout = new MemoryLog()
            {
                Timestamp = false
            };
            var stderr  = new ConsoleLog();
            var timeout = TimeSpan.FromSeconds(30);

            var result = RunAsyncInternal(process, log, stdout, stderr, timeout).GetAwaiter().GetResult();

            if (!result.Succeeded)
            {
                throw new Exception("Failed to detect Xcode path from xcode-select!");
            }

            // Something like /Applications/Xcode114.app/Contents/Developers
            var xcodeRoot = stdout.ToString().Trim();

            if (string.IsNullOrEmpty(xcodeRoot))
            {
                throw new Exception("Failed to detect Xcode path from xcode-select!");
            }

            // We need /Applications/Xcode114.app only
            return(Path.GetDirectoryName(Path.GetDirectoryName(xcodeRoot)));
        }
예제 #2
0
    public static void DoLogToFile(bool done, string logfile)
    {
        if (done)
        {
            if (stream != null)
            {
                Log.Warning("Log.DoLogToFile can be invoked only once");
                return;
            }

            try
            {
                BackupPrevLogs(logfile, MAX_BACKUP_LOGFILE_NUM);
                stream = new StreamWriter(FileUtils.OpenWrite(logfile));
            }
            catch (Exception e)
            {
                Log.Warning("Can not open file {0} for log, {1}", logfile, e);
                return;
            }

            if (memoryLog != null)
            {
                memoryLog.MoveMemoryLogToFile(stream);
                memoryLog = null;
            }
            OnLogEvent += OnLogToFile;
        }
        else
        {
            OnLogEvent -= OnLogToFile;
        }
    }
예제 #3
0
        /// <summary>
        /// デバッグ用に思考エンジンとやりとりしているログを画面上に表示するためのダイアログ。
        /// </summary>
        /// <param name="log"></param>
        public DebugWindow(MemoryLog log)
        {
            InitializeComponent();

            var ListAdded_ = new ListAddedEventHandler(args =>
            {
                try
                {
                    // UIスレッドからの呼び出しを保証する。
                    TheApp.app.UIThread(() => ListAdded(args));
                }
                catch { } // 終了間際だとInvoke()で例外が出るかもしれないので握りつぶしておく。
            });

            log.AddHandler(ListAdded_, ref log_list);
            FormClosed += (sender, args) => { log.RemoveHandler(ListAdded_); };
            memory_log  = log;

            UpdateListBox();

            // すぐに入力出来るようにフィルター用のテキストボックスにフォーカスを移動させておく。
            ActiveControl = textBox1;

            FontUtility.ReplaceFont(this, TheApp.app.Config.FontManager.DebugWindow);
        }
예제 #4
0
        private void RunBuild()
        {
            try
            {
                if (_builder != null)
                {
                    _builder.Build();
                }
                else if (_dungeonBuilder != null)
                {
                    var log  = new MemoryLog();
                    var mesh = _dungeonBuilder.Build(log);

                    if (Directory.Exists(_dungeonBuilder.Dungeon))
                    {
                        Directory.Delete(_dungeonBuilder.Dungeon, true);
                    }
                    Directory.CreateDirectory(_dungeonBuilder.Dungeon);
                    log.WriteToFile(_dungeonBuilder.Dungeon + "\\Build.log");
                    if (mesh != null)
                    {
                        File.WriteAllBytes(_dungeonBuilder.Dungeon + "\\" + _dungeonBuilder.Dungeon + ".dmesh", mesh);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Mesh Builder Interface - Exception");
            }
        }
예제 #5
0
        public async Task MessagesStillLogWhenSendTimesOut()
        {
            var logger   = new MemoryLog();
            var received = 0;
            var timeout  = TimeSpan.FromMilliseconds(100);

            var endpoint = TestConfig.ServerEndpoint();

            using (var server = new TcpServer(endpoint.Ip.Port, TestConfig.Log))
                using (var conn = new Connection(endpoint, new ConnectionConfiguration(requestTimeout: timeout, onRead: (e, read, elapsed) => Interlocked.Increment(ref received)), logger))
                {
                    await Task.WhenAny(server.ClientConnected, Task.Delay(TimeSpan.FromSeconds(3)));

                    server.OnReceivedAsync = async data => {
                        var context = KafkaDecoder.DecodeHeader(data.Skip(Request.IntegerByteSize));
                        await Task.Delay(timeout);

                        await server.SendDataAsync(KafkaDecoder.EncodeResponseBytes(context, new MetadataResponse()));
                    };

                    await AssertAsync.Throws <TimeoutException>(() => conn.SendAsync(new MetadataRequest(), CancellationToken.None));

                    await AssertAsync.ThatEventually(() => received > 0, () => $"received {received}");

                    await AssertAsync.ThatEventually(() => logger.LogEvents.Any(e => e.Item1 == LogLevel.Debug && e.Item2.Message.StartsWith("Timed out -----> (timed out or otherwise errored in client)")), () => logger.ToString(LogLevel.Debug));
                }
        }
예제 #6
0
 public void CopyFromMemoryLog(MemoryLog memoryLog)
 {
     if (memoryLog != null)
     {
         logs.AddRange(memoryLog.logs);
     }
 }
예제 #7
0
        public EntitySession(OperationContext context, EntitySessionOptions options = EntitySessionOptions.Default)
        {
            Context         = context;
            this.Options    = options;
            IsSecureSession = this is Vita.Entities.Authorization.SecureSession;
            _appEvents      = Context.App.AppEvents;
            this.LocalLog   = Context.LocalLog;
            // Multithreaded sessions must be readonly
            var isConcurrent = Options.IsSet(EntitySessionOptions.Concurrent);

            IsReadOnly    = Options.IsSet(EntitySessionOptions.ReadOnly) || isConcurrent;
            _timeService  = Context.App.GetService <ITimeService>();
            _operationLog = Context.App.GetService <IOperationLogService>();
            RecordsLoaded = new EntityRecordWeakRefTable(isConcurrent);
            // These two lists are not used in Readonly sessions
            if (!IsReadOnly)
            {
                RecordsChanged      = new List <EntityRecord>();
                ListsChanged        = new List <IPropertyBoundList>();
                RecordsToClearLists = new HashSet <EntityRecord>();
                ScheduledCommands   = new List <ScheduledLinqCommand>();
            }
            _appEvents.OnNewSession(this);
            //These might be reset in SaveChanges
            NextTransactionId   = Guid.NewGuid();
            TransactionDateTime = _timeService.UtcNow;
            TransactionStart    = _timeService.ElapsedMilliseconds;
        }
예제 #8
0
    public async Task <string> GetAppBundlePath(ILog log, string bundleIdentifier, CancellationToken cancellationToken)
    {
        log.WriteLine($"Querying '{Name}' for bundle path of '{bundleIdentifier}'..");

        var output = new MemoryLog()
        {
            Timestamp = false
        };
        var result = await _processManager.ExecuteXcodeCommandAsync(
            "simctl",
            new[] { "get_app_container", UDID, bundleIdentifier },
            log,
            output,
            output,
            TimeSpan.FromSeconds(30));

        if (!result.Succeeded)
        {
            throw new Exception($"Failed to get information for '{bundleIdentifier}'. Please check the app is installed");
        }

        var bundlePath = output.ToString().Trim();

        log.WriteLine($"Found installed app bundle at '{bundlePath}'");

        return(bundlePath);
    }
예제 #9
0
        public async Task ShouldRetryWhenReceiveAnRetryErrorCode(ErrorCode errorCode)
        {
            var conn = Substitute.For <IConnection>();

            conn.SendAsync(Arg.Any <IRequest <MetadataResponse> >(), Arg.Any <CancellationToken>())
            .Returns(x => CreateMetadataResponse(errorCode), x => CreateMetadataResponse(errorCode));

            var router = GetRouter(conn);
            var log    = new MemoryLog();

            router.Log.ReturnsForAnyArgs(log);
            var response = await router.GetMetadataAsync(new MetadataRequest("Test"), CancellationToken.None);

            Received.InOrder(() =>
            {
                conn.SendAsync(Arg.Any <IRequest <MetadataResponse> >(), Arg.Any <CancellationToken>());
                //_log.OnLogged(LogLevel.Warn, It.Is<LogEvent>(e => e.Message.StartsWith("Failed metadata request on attempt 0: Will retry in")));
                conn.SendAsync(Arg.Any <IRequest <MetadataResponse> >(), Arg.Any <CancellationToken>());
                //_log.OnLogged(LogLevel.Warn, It.Is<LogEvent>(e => e.Message.StartsWith("Failed metadata request on attempt 1: Will retry in")));
                conn.SendAsync(Arg.Any <IRequest <MetadataResponse> >(), Arg.Any <CancellationToken>());
            });

            Assert.That(log.LogEvents.Any(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith("Failed metadata request on attempt 0: Will retry in 00:00:00")));
            Assert.That(log.LogEvents.Any(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith("Failed metadata request on attempt 1: Will retry in 00:00:00")));
            Assert.That(log.LogEvents.Any(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith("Failed metadata request on attempt 2: Will retry in 00:00:00")), Is.False);
            Assert.That(log.LogEvents.Count(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith("Failed metadata request on attempt")), Is.EqualTo(3));
        }
예제 #10
0
        static IEnumerable <string> GetModifiedFilesLocally(IProcessManager processManager, Harness harness, int pull_request)
        {
            var base_commit = $"origin/pr/{pull_request}/merge^";
            var head_commit = $"origin/pr/{pull_request}/merge";

            harness.Log("Fetching modified files for commit range {0}..{1}", base_commit, head_commit);

            if (string.IsNullOrEmpty(head_commit) || string.IsNullOrEmpty(base_commit))
            {
                return(null);
            }

            using (var git = new Process()) {
                git.StartInfo.FileName  = "git";
                git.StartInfo.Arguments = $"diff-tree --no-commit-id --name-only -r {base_commit}..{head_commit}";
                var output = new MemoryLog();
                var rv     = processManager.RunAsync(git, harness.HarnessLog, stdoutLog: output, stderrLog: output).Result;
                if (rv.Succeeded)
                {
                    return(output.ToString().Split(new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries));
                }

                harness.Log("Could not fetch commit range:");
                harness.Log(output.ToString());

                return(null);
            }
        }
예제 #11
0
        public async Task ReadShouldIgnoreMessageWithUnknownCorrelationId()
        {
            const int correlationId = 99;
            var       receivedData  = false;

            var mockLog = new MemoryLog();

            var config   = new ConnectionConfiguration(onRead: (e, buffer, elapsed) => receivedData = true);
            var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog);

            using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port))
                using (var socket = new TcpSocket(endpoint, config, mockLog))
                    using (var conn = new Connection(socket, config, log: mockLog))
                    {
                        //send correlation message
                        server.SendDataAsync(CreateCorrelationMessage(correlationId)).Wait(TimeSpan.FromSeconds(5));

                        //wait for connection
                        await TaskTest.WaitFor(() => server.ConnectionEventcount > 0);

                        Assert.That(server.ConnectionEventcount, Is.EqualTo(1));

                        await TaskTest.WaitFor(() => receivedData);

                        // shortly after receivedData, but still after
                        await TaskTest.WaitFor(() => mockLog.LogEvents.Any(e => e.Item1 == LogLevel.Warn && e.Item2.Message == $"Unexpected response from {endpoint} with correlation id {correlationId} (not in request queue)."));
                    }
        }
예제 #12
0
        public DefaultRegistry()
        {
            Scan(
                scan => {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.With(new ControllerConvention());
            });

            var log = new MemoryLog();

            For <ILog>().Use(log);
            For <IMemoryLog>().Use(log);

            For <IConfigReader>()
            .Use <ExampleJsonConfigReader>()
            .Singleton();

            For <IConfiguration>()
            .Use <ExampleConfiguration>();

            For <INoobotHost>()
            .Use(x => x.GetInstance <NoobotHost>().Start())
            .Singleton();

            For <IContainerFactory>()
            .Use(x => new ContainerFactory(x.GetInstance <IConfiguration>(), x.GetInstance <IConfigReader>(), x.GetInstance <ILog>()));
        }
예제 #13
0
        public async Task ReadShouldIgnoreMessageWithUnknownCorrelationId()
        {
            const int correlationId = 99;
            var       onRead        = 0;

            var log = new MemoryLog();

            var config   = new ConnectionConfiguration(onRead: (e, buffer, elapsed) => Interlocked.Increment(ref onRead));
            var endpoint = TestConfig.ServerEndpoint();

            using (var server = new TcpServer(endpoint.Ip.Port, TestConfig.Log))
                using (var conn = new Connection(endpoint, config, log: log))
                {
                    //send correlation message
                    await server.SendDataAsync(new ArraySegment <byte>(CreateCorrelationMessage(correlationId)));

                    //wait for connection
                    await Task.WhenAny(server.ClientConnected, Task.Delay(TimeSpan.FromSeconds(3)));

                    await AssertAsync.ThatEventually(() => onRead > 0, () => $"read attempts {onRead}");

                    // shortly after receivedData, but still after
                    await AssertAsync.ThatEventually(() => log.LogEvents.Any(e => e.Item1 == LogLevel.Warn && e.Item2.Message == $"Unexpected response (id {correlationId}, 4? bytes) from {endpoint}"), log.ToString);
                }
        }
예제 #14
0
        protected async Task <(bool Succeeded, string Stdout)> ExecuteCommand(
            string filename,
            TimeSpan?timeout = null,
            params string[] arguments)
        {
            var stdoutLog = new MemoryLog()
            {
                Timestamp = false
            };
            var stderrLog = new MemoryLog()
            {
                Timestamp = false
            };

            var result = await _processManager.ExecuteCommandAsync(
                filename,
                arguments,
                new CallbackLog(m => Logger.LogDebug(m)),
                stdoutLog,
                stderrLog,
                timeout ?? TimeSpan.FromSeconds(30));

            string stderr = stderrLog.ToString();

            if (stderr.Length > 0)
            {
                Logger.LogDebug("Error output:" + Environment.NewLine + stderr);
            }

            return(result.Succeeded, stdoutLog.ToString());
        }
        /// <summary>
        /// 先提交数据到数据库,成功后要调用AddDeltaToMemory方法
        /// </summary>
        /// <param name="deltaInfo"></param>
        /// <param name="db"></param>
        /// <param name="transaction"></param>
        public void AddDeltaToDB(XH_CapitalAccountTable_DeltaInfo deltaInfo, Database db, DbTransaction transaction)
        {
            deltaInfo.DeltaTime = DateTime.Now;

            MemoryLog.WriteXHCapitalInfo(deltaInfo);

            AddChangeToDB(deltaInfo, db, transaction);
        }
예제 #16
0
 public override void Exit()
 {
     if (memoryLog != null)
     {
         Log.OnLogEvent -= OnLogToConsolePage;
         memoryLog       = null;
     }
 }
        /// <summary>
        /// 对现货资金表添加一条增量数据,同时提交数据到数据库和内存
        /// </summary>
        /// <param name="deltaInfo"></param>
        /// <returns></returns>
        public bool AddDelta(XH_CapitalAccountTable_DeltaInfo deltaInfo)
        {
            deltaInfo.DeltaTime = DateTime.Now;

            MemoryLog.WriteXHCapitalInfo(deltaInfo);

            return(AddChange(deltaInfo));
        }
예제 #18
0
        public async Task ShouldStartReadPollingOnConstruction()
        {
            var log      = new MemoryLog();
            var endpoint = TestConfig.ServerEndpoint();

            using (new Connection(endpoint, log: log)) {
                await AssertAsync.ThatEventually(() => log.LogEvents.Any(e => e.Item1 == LogLevel.Info && e.Item2.Message.StartsWith("Connecting to")), log.ToString);
            }
        }
예제 #19
0
 public OperationContext(EntityApp app, UserInfo user         = null, WebCallContext webContext = null,
                         DbConnectionReuseMode connectionMode = DbConnectionReuseMode.NoReuse)
 {
     App              = app;
     User             = user ?? UserInfo.Anonymous;
     WebContext       = webContext;
     DbConnectionMode = connectionMode;
     LocalLog         = new MemoryLog(this);
     Disposables      = new ConcurrentDisposableSet();
 }
예제 #20
0
 //Used for creating System-level context within user operation
 public OperationContext(OperationContext parentContext, UserInfo user)
 {
     App              = parentContext.App;
     User             = user;
     WebContext       = parentContext.WebContext;
     LocalLog         = parentContext.LocalLog;
     UserSession      = parentContext.UserSession;
     DataSourceName   = parentContext.DataSourceName;
     DbConnectionMode = parentContext.DbConnectionMode;
     Disposables      = parentContext.Disposables;
 }
        public void InitializeTest()
        {
            var parser = new AppBundleInformationParser();

            var log            = new MemoryLog();
            var processManager = new Mock <IProcessManager> ();
            var info           = parser.ParseFromProjectAsync(log, processManager.Object, projectFilePath, TestTarget.Simulator_iOS64, "Debug").Result;

            Assert.AreEqual(appName, info.AppName);
            Assert.AreEqual(appPath, info.AppPath);
            Assert.AreEqual(appPath, info.LaunchAppPath);
            Assert.AreEqual(appName, info.BundleIdentifier);
        }
        /// <summary>
        /// 先检查再加变化量
        /// </summary>
        /// <param name="func"></param>
        /// <param name="deltaInfo"></param>
        /// <param name="db"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public bool CheckAndAddDelta(Func <XH_CapitalAccountTableInfo, XH_CapitalAccountTable_DeltaInfo, bool> func, XH_CapitalAccountTable_DeltaInfo deltaInfo, Database db, DbTransaction transaction)
        {
            deltaInfo.DeltaTime = DateTime.Now;

            bool isSuccess = CheckAndAddChange(func, deltaInfo, db, transaction);

            if (isSuccess)
            {
                MemoryLog.WriteXHCapitalInfo(deltaInfo);
            }

            return(isSuccess);
        }
예제 #23
0
    public async Task ProcessShouldBeKilled()
    {
        var pm = ProcessManagerFactory.CreateProcessManager();

        var process = new Process();

        process.StartInfo.FileName  = "ping";
        process.StartInfo.Arguments = "-t 127.0.0.1";
        var log = new MemoryLog();

        var result = await pm.RunAsync(process, log, TimeSpan.FromSeconds(3));

        Assert.True(result.TimedOut);
    }
예제 #24
0
    public static MemoryLog CloneMemoryLog()
    {
        var _memoryLog = new MemoryLog();

        if (memoryLog != null)
        {
            _memoryLog.CopyFromMemoryLog(memoryLog);
        }
        else
        {
            _memoryLog.CopyFromFile(FileUtils.log_file(0));
        }
        return(_memoryLog);
    }
예제 #25
0
        public async Task ShouldFinishPartiallyReadMessage()
        {
            var log         = new MemoryLog();
            var bytesRead   = 0;
            var firstLength = 99;

            var config = new ConnectionConfiguration(onReadBytes: (e, attempted, actual, elapsed) => {
                if (Interlocked.Add(ref bytesRead, actual) == firstLength)
                {
                    throw new OutOfMemoryException();
                }
            });

            var endpoint = TestConfig.ServerEndpoint();

            using (var server = new TcpServer(endpoint.Ip.Port, TestConfig.Log))
                using (new Connection(endpoint, config, log))
                {
                    // send size
                    var size = 200;
                    await server.SendDataAsync(new ArraySegment <byte>(size.ToBytes()));

                    var bytes = new byte[size];
                    new Random(42).NextBytes(bytes);
                    var offset        = 0;
                    var correlationId = 200;
                    foreach (var b in correlationId.ToBytes())
                    {
                        bytes[offset++] = b;
                    }

                    // send half of payload
                    await server.SendDataAsync(new ArraySegment <byte>(bytes, 0, firstLength));

                    await AssertAsync.ThatEventually(() => bytesRead >= firstLength, () => $"read {bytesRead}, length {bytes.Length}");

                    Assert.That(log.LogEvents.Count(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith($"Unexpected response (id {correlationId}, {size}? bytes) from")), Is.EqualTo(1), log.ToString());
                    Assert.That(log.LogEvents.Count(e => e.Item1 == LogLevel.Debug && e.Item2.Message.StartsWith($"Received {size} bytes (id {correlationId})")), Is.EqualTo(0));

                    // send half of payload should be skipped
                    while (!await server.SendDataAsync(new ArraySegment <byte>(bytes, firstLength, size - firstLength)))
                    {
                        // repeat until the connection is all up and working ...
                    }
                    await AssertAsync.ThatEventually(() => bytesRead >= size, () => $"read {bytesRead}, size {size}");

                    await AssertAsync.ThatEventually(() => log.LogEvents.Count(e => e.Item1 == LogLevel.Info && e.Item2.Message.StartsWith($"Received {size} bytes (id {correlationId})")) == 1, log.ToString);
                }
        }
예제 #26
0
    public void CopyFromMemoryLog(MemoryLog memoryLog)
    {
        if (memoryLog == null)
        {
            return;
        }
        var _logs = memoryLog.logs.ToArray();

        if (_logs != null)
        {
            foreach (var log in _logs)
            {
                logs.Add(log);
            }
        }
    }
예제 #27
0
        public async Task TimedOutQueueIsClearedWhenTooBig()
        {
            var logger  = new MemoryLog();
            var timeout = TimeSpan.FromMilliseconds(1);

            var endpoint = TestConfig.ServerEndpoint();

            using (var server = new TcpServer(endpoint.Ip.Port, TestConfig.Log))
                using (var conn = new Connection(endpoint, new ConnectionConfiguration(requestTimeout: timeout), logger)) {
                    await Task.WhenAny(server.ClientConnected, Task.Delay(TimeSpan.FromSeconds(3)));

                    await AssertAsync.Throws <TimeoutException>(() => Task.WhenAll(Enumerable.Range(0, 201).Select(i => conn.SendAsync(new MetadataRequest(), CancellationToken.None))));

                    await AssertAsync.ThatEventually(() => logger.LogEvents.Any(e => e.Item1 == LogLevel.Debug && e.Item2.Message.StartsWith("Clearing timed out requests to avoid overflow")), () => logger.ToString(LogLevel.Debug));
                }
        }
예제 #28
0
        public async Task KafkaConnectionShouldSkipPartiallyReadMessage()
        {
            var mockLog   = new MemoryLog();
            var bytesRead = 0;

            var config = new ConnectionConfiguration(onReadChunk: (e, size, remaining, read, elapsed) => Interlocked.Add(ref bytesRead, read));

            var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog);

            using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port))
                using (var socket = new TcpSocket(endpoint, config, TestConfig.InfoLog))
                    using (new Connection(socket, config, log: mockLog))
                    {
                        // send size
                        var size = 200;
                        await server.SendDataAsync(size.ToBytes());

                        var randomizer = Randomizer.CreateRandomizer();
                        var firstBytes = new byte[99];
                        for (var i = 0; i < firstBytes.Length; i++)
                        {
                            firstBytes[i] = randomizer.NextByte();
                        }

                        // send half of payload
                        await server.SendDataAsync(firstBytes);

                        await TaskTest.WaitFor(() => bytesRead == firstBytes.Length);

                        //Assert.That(mockLog.LogEvents.Count(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith("Skipping")), Is.EqualTo(0));

                        server.DropConnection();

                        // send half of payload should be skipped
                        var lastBytes = new byte[size];
                        for (var i = 0; i < lastBytes.Length; i++)
                        {
                            lastBytes[i] = randomizer.NextByte();
                        }
                        await server.SendDataAsync(lastBytes);

                        await TaskTest.WaitFor(() => bytesRead >= size);

                        Assert.That(mockLog.LogEvents.Count(e => e.Item1 == LogLevel.Warn && e.Item2.Message.StartsWith($"Skipping {size - firstBytes.Length} bytes on")), Is.EqualTo(1));
                    }
        }
예제 #29
0
        public async Task ShouldLogDisconnectAndRecover()
        {
            var log = new MemoryLog();
            var clientDisconnected = 0;
            var clientConnected    = 0;
            var serverConnected    = 0;

            var config = new ConnectionConfiguration(
                onDisconnected: (e, exception) => {
                Interlocked.Increment(ref clientDisconnected);
            },
                onConnected: (e, attempt, elapsed) => {
                Interlocked.Increment(ref clientConnected);
            });

            var endpoint = TestConfig.ServerEndpoint();

            using (var server = new TcpServer(endpoint.Ip.Port, TestConfig.Log)
            {
                OnConnected = () => Interlocked.Increment(ref serverConnected)
            })
                using (new Connection(endpoint, config, log: log))
                {
                    for (var connectionAttempt = 1; connectionAttempt <= 4; connectionAttempt++)
                    {
                        var currentAttempt = connectionAttempt;
                        await AssertAsync.ThatEventually(() => serverConnected == currentAttempt, () => $"server {serverConnected}, attempt {currentAttempt}");

                        await server.SendDataAsync(new ArraySegment <byte>(CreateCorrelationMessage(connectionAttempt)));

                        TestConfig.Log.Write(LogLevel.Info, () => LogEvent.Create($"Sent CONNECTION attempt {currentAttempt}"));
                        await AssertAsync.ThatEventually(() => clientConnected == currentAttempt, TimeSpan.FromMilliseconds(200), () => $"client {clientConnected}, attempt {currentAttempt}");

                        await AssertAsync.ThatEventually(() => log.LogEvents.Count(e => e.Item1 == LogLevel.Info && e.Item2.Message.StartsWith("Received 4 bytes (id ")) == currentAttempt, () => $"attempt {currentAttempt}\n" + log.ToString(LogLevel.Info));

                        TestConfig.Log.Write(LogLevel.Info, () => LogEvent.Create($"Dropping CONNECTION attempt {currentAttempt}"));
                        server.DropConnection();
                        await AssertAsync.ThatEventually(() => clientDisconnected == currentAttempt, () => $"client {clientDisconnected}, attempt {currentAttempt}");

                        Assert.That(log.LogEvents.Count(e => e.Item1 == LogLevel.Info && e.Item2.Message.StartsWith("Disposing transport to")), Is.AtLeast(currentAttempt));
                    }
                }
        }
예제 #30
0
 public override void OnGUI()
 {
     if (memoryLog == null)
     {
         memoryLog = Log.CloneMemoryLog();
         Log.Tag tag = Log.Tag.Error;
         while (tag >= Log.logPriority)
         {
             showTagsNum[(int)tag] = memoryLog.Count(tag);
             --tag;
         }
         Log.OnLogEvent += OnLogToConsolePage;
     }
     GUILayout.BeginVertical(GUILayout.Height(GUI.skin.window.padding.top), GUILayout.MinHeight(100));
     DrawToolbar();
     DrawFilter();
     DrawLogList();
     GUILayout.EndVertical();
 }