public void Init()
        {
            if (_connGateway == null)
            {
                switch (GameService.CommandInfo.Protocol)
                {
                case GsEncryptor.TcpSec:
                    _connGateway = new GsTcpClient();
                    break;

                case GsEncryptor.WebSocketSec:
                    _connGateway = new GsWebSocketClient();
                    break;
                }

                if (_connGateway != null)
                {
                    _connGateway.DataReceived += OnDataReceived;
                }
            }

            _cancellationToken = new CancellationTokenSource();


            if (IsInitializing)
            {
                return;
            }

            IsInitializing = true;
            PingUtil.Stop();
            _connGateway?.Init(GameService.CommandInfo, GameService.CommandInfo.Cipher);
        }
        private void OnAuth(object sender, string playerHash)
        {
            DebugUtil.LogNormal <CommandHandler>(DebugLocation.Command, "OnAuth", "CommandHandler OnAuth Done");

            IsInitializing = false;
            PlayerHash     = playerHash;
            _connGateway?.StartSending();
            PingUtil.Start();

            if (_isFirstInit)
            {
                return;
            }
            _isFirstInit = true;

            try
            {
                if (GameService.HandlerType == EventHandlerType.NativeContext)
                {
                    CoreEventHandlers.SuccessfullyLogined?.Invoke(null, null);
                }
                else
                {
                    GameService.SynchronizationContext?.Send(
                        delegate { CoreEventHandlers.SuccessfullyLogined?.Invoke(null, null); }, null);
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }
示例#3
0
        private void WorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            WorkerParam param = doWorkEventArgs.Argument as WorkerParam;

            doWorkEventArgs.Result = new WorkerResult()
            {
                Times    = PingUtil.Ping(param.Address),
                RowIndex = param.RowIndex
            };
        }
示例#4
0
        private void UpdateRow(WorkerResult result)
        {
            PingUtil.AnalyzePingResult(result.Times, out var min, out var max, out var avg);
            var row = dgvResult.Rows[result.RowIndex];

            row.Cells["PingResult"].Value = string.Join(";", result.Times);
            row.Cells["Min"].Value        = min;
            row.Cells["Max"].Value        = max;
            row.Cells["Avg"].Value        = avg;
        }
        private void OnMirror(object sender, Packet packet)
        {
            try
            {
                var currentTime     = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                var lastCurrentTime = long.Parse(packet.Data);

                PingUtil.SetLastPing(currentTime, lastCurrentTime);
            }
            finally
            {
                _retryPingCounter = 0;
                _isPingRequested  = false;
            }
        }
        private void PingServers(LoadBalancerRoute route)
        {
            PingUtil pingUtil = new PingUtil(_loadBalancerContext, _logger);

            if (pingUtil.HasPing)
            {
                foreach (ServerGroup serverGroup in route.ServerGroups)
                {
                    foreach (Server server in serverGroup.Servers)
                    {
                        server.IsAlive = pingUtil.IsAlive(server);
                    }
                }
            }
        }
示例#7
0
        public PingViewModel(Reading reading)
        {
            try
            {
                Host = string.Format("Pinging {0}", reading.Reader.Host);
                Task.Run(() =>
                {
                    while (true)
                    {
                        string info = string.Empty;
                        info       += string.Format("{0}: Pinging {1}...", DateTime.Now.ToString(Consts.TIME_FORMAT), reading.Reader.Host);
                        Application.Current.Dispatcher.Invoke((Action)(() =>
                        {
                            PingInfo += info;
                        }));

                        info = string.Empty;

                        if (PingUtil.PingHost(reading.Reader.Host) == true)
                        {
                            info += string.Format(" OK");
                        }
                        else if (PingUtil.PingHostViaTcp(reading.Reader.Host, Consts.PING_PORT) == true)
                        {
                            info += string.Format(" OK");
                        }
                        else
                        {
                            info += string.Format(" Request Timeout.");
                        }

                        info += Environment.NewLine;
                        Thread.Sleep(50);

                        Application.Current.Dispatcher.Invoke((Action)(() =>
                        {
                            PingInfo += info;
                        }));

                        Thread.Sleep(1500);
                    }
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("{0}:  {1}\n{2}", nameof(PingViewModel), ex.Message, ex.StackTrace));
            }
        }
        public void Dispose(bool isGraceful)
        {
            try
            {
                _isDisposed      = true;
                _isFirstInit     = false;
                _isPingRequested = false;

                IsInitializing = false;

                _retryConnectCounter = 0;
                _retryPingCounter    = 0;

                _cancellationToken?.Cancel(false);
                _observer?.Dispose();
                PingUtil.Dispose();

                _connGateway?.StopReceiving(isGraceful);
            }
            catch (Exception)
            {
                // ignored
            }
            finally
            {
                _connGateway = null;
                PlayerHash   = null;

                CommandEventHandlers.CommandAuthorized        = null;
                CommandEventHandlers.CommandClientConnected   = null;
                CommandEventHandlers.GsCommandClientConnected = null;
                CommandEventHandlers.GsCommandClientError     = null;
                CommandEventHandlers.CommandPing   = null;
                CommandEventHandlers.CommandMirror = null;

                try
                {
                    GC.SuppressFinalize(this);
                }
                catch (Exception)
                {
                    // ignored
                }

                DebugUtil.LogNormal <CommandHandler>(DebugLocation.Command, "Dispose", "CommandHandler Dispose Done");
            }
        }
示例#9
0
        public DefaultServerSourceMonitor(ILoadBalancerContext loadBalancerContext)
        {
            _loadBalancerContext = loadBalancerContext;
            _pingUtil            = new PingUtil(_loadBalancerContext, _logger);

            var    configurationManager = _loadBalancerContext.ConfigurationManager;
            string prefix = _loadBalancerContext.LoadBalancerKey;

            CheckIntervalInMillisecondProperty = configurationManager.GetProperty <int?>(prefix + "." + ConfigurationKeys.CheckInterval);
            FailureThresholdPercentageProperty = configurationManager.GetProperty <int?>(prefix + "." + ConfigurationKeys.FailureThresholdPercentage);

            string globalPrefix = _loadBalancerContext.ManagerId;

            GlobalCheckIntervalInMillisecondProperty = configurationManager.GetProperty <int?>(globalPrefix + "." + ConfigurationKeys.CheckInterval, DefaultCheckInterval);
            GlobalFailureThresholdPercentageProperty = configurationManager.GetProperty <int?>(globalPrefix + "." + ConfigurationKeys.FailureThresholdPercentage, DefaultFailureThresholdPercent);

            _checkHealthLatencyMetrics = new ConcurrentDictionary <string, IAuditMetric>();
            _checkHealthEventMetrics   = new ConcurrentDictionary <string, IEventMetric>();
        }
示例#10
0
        public async Task Handle(DoPageLoadMessage notification, CancellationToken cancellationToken)
        {
            var cacheKey  = $"{notification.EndPointId}-{nameof(SensorType.PageLoad)}";
            var operation = await _cache.GetAsync <OngoingOperationDto>(cacheKey);

            if (operation != null)
            {
                if ((DateTime.Now - operation.StartDate).TotalMinutes <= 1)
                {
                    return;
                }
            }
            else
            {
                await _cache.SetAsync(cacheKey, new OngoingOperationDto(DateTime.Now));
            }

            var networkavailability = true;

            var urlResult = WebSiteUtil.IsUrlAlive(notification.PageUrl);

            if (urlResult == false) // check network availability
            {
                networkavailability = PingUtil.Ping("8.8.8.8");
            }

            if (networkavailability == false)
            {
                //TODO Notify about  connection
            }
            else
            {
                await _mediator.Publish(new PageLoadNotificationMessage
                {
                    PageUrl      = notification.PageUrl,
                    EmailNotify  = notification.EmailNotify,
                    EndPointId   = notification.EndPointId,
                    MobileNotify = notification.MobileNotify,
                    LoadSuccess  = urlResult
                }, cancellationToken);
            }
        }
示例#11
0
        public async Task Handle(DoPingMessage notification, CancellationToken cancellationToken)
        {
            var cacheKey  = $"{notification.EndPointId}-{nameof(SensorType.Ping)}";
            var operation = await _cache.GetAsync <OngoingOperationDto>(cacheKey);

            if (operation != null)
            {
                if ((DateTime.Now - operation.StartDate).TotalMinutes <= 1)
                {
                    return;
                }
            }
            else
            {
                await _cache.SetAsync(cacheKey, new OngoingOperationDto(DateTime.Now));
            }

            var networkavailability = true;

            var pingResult = PingUtil.Ping(notification.IpAddress);

            if (pingResult == false) // IS Network availability
            {
                networkavailability = PingUtil.Ping("8.8.8.8");
            }

            if (networkavailability == false)
            {
                //TODO Notify about  connection
            }
            else
            {
                await _mediator.Publish(new PingNotificationMessage
                {
                    IpAddress    = notification.IpAddress,
                    EmailNotify  = notification.EmailNotify,
                    EndPointId   = notification.EndPointId,
                    MobileNotify = notification.MobileNotify,
                    PingSuccess  = pingResult
                }, cancellationToken);
            }
        }
        internal CommandHandler()
        {
            _observer    = new GsLiveSystemObserver(GSLiveType.Command);
            _isDisposed  = false;
            _isFirstInit = false;

            InitRequestMessageHandlers();
            InitResponseMessageHandlers();

            PingUtil.Init();

            // Set Internal Event Handlers
            CommandEventHandlers.CommandPing       += OnPing;
            CommandEventHandlers.CommandAuthorized += OnAuth;
            CommandEventHandlers.CommandMirror     += OnMirror;
            PingUtil.RequestPing += RequestPing;
            CommandEventHandlers.GsCommandClientConnected += OnGsTcpClientConnected;
            CommandEventHandlers.GsCommandClientError     += OnGsTcpClientError;

            DebugUtil.LogNormal <CommandHandler>(DebugLocation.Command, "Constructor", "CommandHandler Initialized");
        }
        public Task StartReading()
        {
            try
            {
                bool isPingable = false;
                while (!isPingable && !_cancellationToken.IsCancellationRequested)
                {
                    isPingable = PingUtil.PingHostViaTcp(_reading.Reader.Host, int.Parse(_reading.Reader.Port));
                }

                if (isPingable)
                {
                    return(backgoundWorker = Task.Run(() => DoReadingWork(_cancellationToken.Token), _cancellationToken.Token));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("{0}:  {1}\n{2}", nameof(StartReading), ex.Message, ex.StackTrace));
            }

            return(backgoundWorker);
        }
示例#14
0
        public void DoWork()
        {
            startedWorksCount  = 0;
            finishedWorksCount = 0;

            foreach (KeyValuePair <string, MachineConnectivity> keyValue in connectivityResults)
            {
                MachineConnectivity connectivity = keyValue.Value;

                if (connectivity.CanPing ?? false)
                {
                    continue;
                }

                startedWorksCount++;

                string machineName = keyValue.Key;
                BackgroundWork <bool> .CreateWork(window, () => { },
                                                  () =>
                {
                    return(PingUtil.PingHost(machineName));
                },
                                                  (taskResult) =>
                {
                    bool result = false;
                    if (taskResult.HasError)
                    {
                        result = false;
                    }
                    else
                    {
                        result = taskResult.Result;
                    }

                    ConsolidatePingResult(machineName, result);
                }
                                                  ).Execute();
            }

            foreach (KeyValuePair <string, MachineConnectivity> keyValue in connectivityResults)
            {
                MachineConnectivity connectivity = keyValue.Value;

                if (connectivity.CanRemotePathAccess ?? false)
                {
                    continue;
                }

                startedWorksCount++;

                string machineName = keyValue.Key;
                string userName    = connectivity.Machine.Credential?.UserName;
                string password    = connectivity.Machine.Credential?.LoginPlainPassword;

                NetworkFileAccess fileAccess = new NetworkFileAccess(machineName, userName, password);

                BackgroundWork.CreateWork(window, () => { },
                                          () =>
                {
                    fileAccess.EnsureDirectory(testingFolderPath);
                    fileAccess.CanAccessDirectory(testingFolderPath);
                    return(0);
                },
                                          (taskResult) =>
                {
                    bool result = true;
                    if (taskResult.HasError)
                    {
                        logger.Error($"Testing of RemotePathAccess failed for machine [{ machineName }]. Message: { taskResult.Exception.ToString() }");
                        result = false;
                    }

                    ConsolidateRemotePathAccessResult(machineName, result);
                }
                                          ).Execute();
            }

            foreach (KeyValuePair <string, MachineConnectivity> keyValue in connectivityResults)
            {
                MachineConnectivity connectivity = keyValue.Value;
                MinerMachine        machine      = connectivity.Machine;
                if (connectivity.CanRemotePowershell ?? false)
                {
                    continue;
                }

                startedWorksCount++;

                string machineName = keyValue.Key;

                BackgroundWork.CreateWork(window, () => { },
                                          () =>
                {
                    TargetMachineExecutor executor = TargetMachineExecutor.GetExecutor(machineName);
                    if (machine.Credential != null)
                    {
                        executor.SetCredential(machine.Credential.UserName, machine.Credential.LoginPlainPassword);
                    }

                    executor.TestConnection();
                    return(0);
                },
                                          (taskResult) =>
                {
                    bool result = true;
                    if (taskResult.HasError)
                    {
                        logger.Error($"Testing of RemotePathAccess failed for machine [{ machineName }]. Message: { taskResult.Exception.ToString() }");
                        result = false;
                    }

                    ConsolidateRemotePowershellResult(machineName, result);
                }
                                          ).Execute();
            }

            while (finishedWorksCount < startedWorksCount)
            {
                Thread.Sleep(30);
            }
        }
 internal static short GetPing()
 {
     return(PingUtil.GetLastPing());
 }