Ejemplo n.º 1
0
        public async Task <PingDataPoint> PingServerAsync(PingSetting setting)
        {
            using (var httpClient = _factory.BuildClient())
            {
                TimeSpan       responseTime;
                HttpStatusCode statusCode = HttpStatusCode.ServiceUnavailable;

                // Generate a request
                var httpContent = new HttpRequestMessage(
                    setting.GetMethodRequired ? HttpMethod.Get : HttpMethod.Head,
                    setting.ServerUrl
                    );

                var timer = new Stopwatch();
                timer.Start();

                var task = httpClient.SendAsync(httpContent);
                // Make sure task finishes in TotalMilliseconds milliseconds
                if (
                    await Task.WhenAny(
                        task,
                        Task.Delay(Convert.ToInt32(setting.MaxResponseTime.TotalMilliseconds))
                        ) == task
                    )
                {
                    var response = await task;

                    timer.Stop();

                    // Record time and code
                    responseTime = timer.Elapsed;
                    statusCode   = response.StatusCode;
                }

                if (
                    statusCode == HttpStatusCode.ServiceUnavailable ||
                    responseTime > setting.MaxResponseTime
                    )
                {
                    // Timeout/cancellation logic
                    // If problem occurred then set service unavailable.
                    responseTime = new TimeSpan(0);
                    statusCode   = HttpStatusCode.ServiceUnavailable;

                    // _logger.LogWarning(LoggingEvents.Ping.AsInt(), $"Resource {setting.ServerUrl} is unavailable. See stack trace.");
                }

                _logger.LogDebug(LoggingEvents.Ping.AsInt(), $"Ping completed for {setting.ServerUrl}");

                var metric = await _metrics.GetOrCreateMetricAsync(Metrics.Ping, new Uri(setting.ServerUrl).Host);

                return(new PingDataPoint
                {
                    Metric = metric,
                    ResponseTime = responseTime,
                    Success = statusCode.AsInt() / 100 == 2,                     // 2xx
                    Message = statusCode.AsInt() / 100 == 2 ? "OK" : "Failure"
                });
            }
        }
Ejemplo n.º 2
0
        public async Task SendMessageAsync(string message)
        {
            if (Convert.ToBoolean(_config["Secrets:Slack:Enabled"]))
            {
                using (var client = _factory.BuildClient())
                {
                    try
                    {
                        var response = await client.PostAsync(
                            _config["Secrets:Slack:WebHook"],
                            new StringContent(
                                JsonConvert.SerializeObject(new { text = message }),
                                Encoding.UTF8,
                                "application/json"
                                )
                            );

                        response.EnsureSuccessStatusCode();

                        _logger.LogDebug($"Message '{message.Truncate(20)}' has been sent through Slack");
                    }
                    catch (System.Exception e)
                    {
                        _logger.LogError(LoggingEvents.Notifications.AsInt(), e, "Could not send slack message");
                    }
                }
            }
            else
            {
                _logger.LogInformation(LoggingEvents.Notifications.AsInt(), $"Message '{message}' was supposed to be sent through Slack");
            }
        }
Ejemplo n.º 3
0
        public async Task <PingDataPoint> PingServerAsync(PingSetting setting)
        {
            using (var client = _factory.BuildClient())
            {
                var parameters = new Dictionary <string, string> {
                    { "url", setting.ServerUrl },
                    { "method", setting.GetMethodRequired ? "GET" : "HEAD" },
                    { "timeout", setting.MaxResponseTime.TotalMilliseconds.ToString() }
                };

                var result = await client.GetAsync(QueryHelpers.AddQueryString(_conf["Data:PingServerUrl"], parameters));

                var data = JsonConvert.DeserializeObject <RemotePingServerResponse>(
                    await result.Content.ReadAsStringAsync()
                    );

                _logger.LogDebug(LoggingEvents.Ping.AsInt(), $"Ping completed for {setting.ServerUrl}");

                var metric = await _metrics.GetOrCreateMetricAsync(Metrics.Ping, new Uri(setting.ServerUrl).Host);

                return
                    (data.IsError ?
                     new PingDataPoint
                {
                    Metric = metric,
                    ResponseTime = new TimeSpan(0),
                    Success = data.StatusCode / 100 == 2,                             // 2xx
                    Message = data.Error
                }:
                     new PingDataPoint
                {
                    Metric = metric,
                    ResponseTime = new TimeSpan(0, 0, 0, 0, data.Latency),
                    Success = data.StatusCode / 100 == 2,                             // 2xx
                    Message = "OK"
                });
            }
        }
Ejemplo n.º 4
0
        public async Task <IEnumerable <RawMemoryPool> > GetRawMemPool(bool verboseOutput = false)
        {
            var httpClient = _httpClientFactory.BuildClient();
            var jParams    = new JArray();

            jParams.Add(verboseOutput ? 0 : 1);
            var jObj = new JObject();

            jObj.Add("id", Guid.NewGuid().ToString());
            jObj.Add("method", Constants.RpcOperations.Getrawmempool);
            jObj.Add("params", jParams);
            var content = new StringContent(jObj.ToString(), System.Text.Encoding.UTF8, ContentType);
            var request = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                Content    = content,
                RequestUri = GetUri()
            };

            var response = await httpClient.SendAsync(request).ConfigureAwait(false);

            var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var    jsonObj   = JObject.Parse(json);
            string errorCode = null;

            if (TryGetError(jsonObj, out errorCode))
            {
                throw new RpcException(errorCode);
            }

            var resultObj = jsonObj.GetValue("result") as JArray;

            return(ExtractRawMemPool(resultObj));
        }