public async Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(AzureServiceBusQueueLiveness)} is checking the Azure Event Hub.");

                var queueClient = new QueueClient(_connectionString,
                                                  _queueName,
                                                  ReceiveMode.PeekLock);

                var scheduledMessageId = await queueClient.ScheduleMessageAsync(
                    new Message(Encoding.UTF8.GetBytes(TEST_MESSAGE)),
                    new DateTimeOffset(DateTime.UtcNow).AddHours(2));

                await queueClient.CancelScheduledMessageAsync(scheduledMessageId);

                _logger?.LogInformation($"The {nameof(AzureServiceBusQueueLiveness)} check success.");

                return(LivenessResult.Healthy());
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(AzureServiceBusQueueLiveness)} check fail for {_connectionString} with the exception {ex.ToString()}.");

                return(LivenessResult.UnHealthy(ex));
            }
        }
Ejemplo n.º 2
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
        {
            return(await Task.Run(() =>
            {
                IDictionary <string, Object> data = new Dictionary <string, object>();
                data.Add("type", "ServiceBusHealthCheck");
                // data.Add("connectionString", this.connectionString);
                data.Add("topicName", this.topicName);
                try
                {
                    if (serviceBusHealthCheckType == ServiceBusHealthCheckType.Receive)
                    {
                        data.Add("subscriptionName", this.subscriptionName);
                        var subscriptionClient = new SubscriptionClient(ListenConnectionString, topicName, subscriptionName);
                        var clientid = subscriptionClient.ClientId;
                        data.Add("clientid", clientid);

                        var rulestask = subscriptionClient.GetRulesAsync();
                        rulestask.Wait();
                        data.Add("rules", string.Join(",", rulestask.Result));
                    }
                    else
                    {
                        var topicClient = new QueueClient(SendConnectionString, topicName);
                        var clientid = topicClient.ClientId;
                        data.Add("clientid", clientid);
                        var list = topicClient.Path;

                        Message mes = new Message();
                        mes.Body = System.Text.Encoding.UTF8.GetBytes("TestMessage");

                        var sendtask = topicClient.ScheduleMessageAsync(mes, DateTime.Now.AddDays(100));
                        sendtask.Wait();

                        var cancell = topicClient.CancelScheduledMessageAsync(sendtask.Result);
                        cancell.Wait();
                    }

                    string description = $"ServiceBus namespace {nameSpace}.servicebus.windows.net is healthy";
                    ReadOnlyDictionary <string, Object> rodata = new ReadOnlyDictionary <string, object>(data);
                    return HealthCheckResult.Healthy(description, rodata);
                }
                catch (Exception ex)
                {
                    string description = "ServiceBus is failed with exception " + ex.Message;
                    ReadOnlyDictionary <string, Object> rodata = new ReadOnlyDictionary <string, object>(data);
                    return HealthCheckResult.Unhealthy(description, data: rodata);
                }
            }));
        }
Ejemplo n.º 3
0
        private static async Task Genereate(DateTime baseTime, int i)
        {
            var scheduleTime = baseTime.AddMinutes(i);

            if (scheduleTime < DateTime.Now)
            {
                return;
            }

            var scheduleUtc = new DateTimeOffset(scheduleTime.ToUniversalTime());

            //var message = new BrokeredMessage(JsonConvert.SerializeObject(myMessage))
            //{
            //    MessageId = scheduleUtc.ToUnixTimeSeconds().ToString(),
            //    ContentType = "application/json"
            //};
            var message = new BrokeredMessage($"Scheduled at {scheduleTime}.")
            {
                MessageId = scheduleUtc.ToUnixTimeSeconds().ToString(),
            };
            var redisKey = $"{RedisKeyPrefix}:{message.MessageId}";
            var oldValue = RedisDb.StringGet(redisKey);

            try
            {
                if (!oldValue.IsNullOrEmpty)
                {
                    await QueueClient.CancelScheduledMessageAsync(long.Parse(oldValue.ToString()));
                }
            }
            catch (Exception e)
            {
                Logger.Error($"Cancel scheduled message failed: {message}.");
                Logger.Error(e.Message);
                return;
            }

            try
            {
                var sequenceNumber = await QueueClient.ScheduleMessageAsync(message, scheduleUtc);

                var newValue = $"{sequenceNumber}";
                await RedisDb.StringSetAsync(redisKey, newValue, scheduleTime.Subtract(DateTime.Now));
            }
            catch (Exception e)
            {
                Logger.Error($"Enqueue scheduled message failed: {message}");
                Logger.Error(e.Message);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Method to run Health Check for Service Bus
        /// </summary>
        /// <param name="serviceKey"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public LightHealth.HealthCheck HealthCheck(string serviceKey, string value)
        {
            try
            {
                if (_topics.Count > 0)
                {
                    foreach (KeyValuePair <MethodInfo, TopicAttribute> item in _topics)
                    {
                        if (!string.IsNullOrEmpty(item.Value.TopicName.ToString()))
                        {
                            TopicClient topicClient = new TopicClient(GetConnection(item), item.Value.TopicName, RetryPolicy.Default);

                            var scheduledMessageId = topicClient.ScheduleMessageAsync(
                                new Message(Encoding.UTF8.GetBytes("HealthCheckTestMessage")),
                                new DateTimeOffset(DateTime.UtcNow).AddHours(2));

                            topicClient.CancelScheduledMessageAsync(scheduledMessageId.Result);
                        }
                    }
                }

                if (_queues.Count > 0)
                {
                    foreach (KeyValuePair <MethodInfo, QueueAttribute> item in _queues)
                    {
                        if (!string.IsNullOrEmpty(item.Value.QueueName.ToString()))
                        {
                            QueueClient queueReceiver      = new QueueClient(GetConnection(item), item.Value.QueueName, ReceiveMode.ReceiveAndDelete);
                            var         scheduledMessageId = queueReceiver.ScheduleMessageAsync(
                                new Message(Encoding.UTF8.GetBytes("HealthCheckTestMessage")),
                                new DateTimeOffset(DateTime.UtcNow).AddHours(2));

                            queueReceiver.CancelScheduledMessageAsync(scheduledMessageId.Result);
                        }
                    }
                }
                return(LightHealth.HealthCheck.Healthy);
            }
            catch
            {
                return(LightHealth.HealthCheck.Unhealthy);
            }
        }
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                var queueClient = new QueueClient(_connectionString,
                                                  _queueName,
                                                  ReceiveMode.PeekLock);

                var scheduledMessageId = await queueClient.ScheduleMessageAsync(
                    new Message(Encoding.UTF8.GetBytes(TEST_MESSAGE)),
                    new DateTimeOffset(DateTime.UtcNow).AddHours(2));

                await queueClient.CancelScheduledMessageAsync(scheduledMessageId);

                return(HealthCheckResult.Healthy());
            }
            catch (Exception ex)
            {
                return(new HealthCheckResult(context.Registration.FailureStatus, exception: ex));
            }
        }
        public async Task <(string, bool)> IsHealthy(HttpContext context, bool isDevelopment, CancellationToken cancellationToken = default)
        {
            try
            {
                var queueClient        = new QueueClient(_connectionString, _queueName, ReceiveMode.PeekLock);
                var scheduledMessageId = await queueClient.ScheduleMessageAsync(
                    new Message(Encoding.UTF8.GetBytes(TEST_MESSAGE)),
                    new DateTimeOffset(DateTime.UtcNow).AddHours(2)
                    );

                await queueClient.CancelScheduledMessageAsync(scheduledMessageId);

                return(BeatPulseKeys.BEATPULSE_HEALTHCHECK_DEFAULT_OK_MESSAGE, true);
            }
            catch (Exception ex)
            {
                var message = !isDevelopment?string.Format(BeatPulseKeys.BEATPULSE_HEALTHCHECK_DEFAULT_ERROR_MESSAGE, Name)
                                  : $"Exception {ex.GetType().Name} with message ('{ex.Message}')";

                return(message, false);
            }
        }
Ejemplo n.º 7
0
        private static Func <ValueTask <HealthCheckResult> > CheckServiceBusQueueConnectivity(string name, QueueClient queueClient)
        {
            return(async() =>
            {
                var result = true;

                try
                {
                    var id = await queueClient.ScheduleMessageAsync(HealthMessage, HealthMessageTestSchedule).ConfigureAwait(false);

                    await queueClient.CancelScheduledMessageAsync(id);
                }
                catch (Exception ex)
                {
                    Logger.ErrorException($"{name} failed.", ex);

                    result = false;
                }

                return result
                    ? HealthCheckResult.Healthy($"OK. '{queueClient.Path}/{queueClient.QueueName}' is available.")
                    : HealthCheckResult.Unhealthy($"Failed. '{queueClient.Path}/{queueClient.QueueName}' is unavailable.");
            });
        }
Ejemplo n.º 8
0
 public Task CancelScheduledSend(long sequenceNumber)
 {
     return(_queueClient.CancelScheduledMessageAsync(sequenceNumber));
 }