Esempio n. 1
0
        static async Task Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console()
                         .CreateLogger();

            var eventProcessorHostControllerSettings = new EventProcessorHostControllerSettings
            {
                ConsumerGroupName        = PartitionReceiver.DefaultConsumerGroupName,
                EventHubConnectionString =
                    "Endpoint=sb://ihsuprodbyres066dednamespace.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=Lwo24+ra9w40Lz2vTS7CBTWsHPhvnKnXf2xPei1AAng=",
                EventHubName            = "iothub-ehub-ps-iothub-906112-75e83745be",
                LeaseContainerName      = "message-processor-host",
                StorageConnectionString =
                    "DefaultEndpointsProtocol=https;AccountName=psiotfmstorage;AccountKey=1uSJY+Uw4jwSEX/DvCFXCXBfxFcFW190madsMGgBr62mh+Q5/VGdJzwo4+512WitehPm0KfTGzn3c/GNfhtbBg==;EndpointSuffix=core.windows.net"
            };

            var eventProcessorHostController = new EventProcessorWrapper(
                new LoggingEventProcessorFactory(Log.Logger, new DeviceEventDataReader()),
                eventProcessorHostControllerSettings);

            await eventProcessorHostController.StartEventProcessorHostAsync();

            Log.Logger.Information("Event processor started. Press ENTER to exit.");
            Console.ReadLine();

            Log.Logger.Information("Shutting down...");

            await eventProcessorHostController.StopEventProcessorHostAsync();

            Log.Logger.Information("Event processor has shut down.");
        }
        /// <summary>
        /// Method that runs asynchronously to connect to event hub and check
        /// a) if all expected value changes are delivered
        /// b) that time between value changes is expected
        /// </summary>
        /// <param name="token">Token to cancel the operation</param>
        /// <returns>Task that run until token is canceled</returns>
        public async Task <StartResult> StartAsync(ValidatorConfiguration configuration)
        {
            _logger.LogInformation("StartAsync called.");
            var sw = Stopwatch.StartNew();

            try {
                // Check if already started.
                if (_cancellationTokenSource != null)
                {
                    return(new StartResult());
                }

                // Check provided configuration.
                if (configuration == null)
                {
                    throw new ArgumentNullException(nameof(configuration));
                }

                if (configuration.ExpectedValueChangesPerTimestamp < 0)
                {
                    throw new ArgumentNullException("Invalid configuration detected, expected value changes per timestamp can't be lower than zero");
                }
                if (configuration.ExpectedIntervalOfValueChanges < 0)
                {
                    throw new ArgumentNullException("Invalid configuration detected, expected interval of value changes can't be lower than zero");
                }
                if (configuration.ExpectedMaximalDuration < 0)
                {
                    throw new ArgumentNullException("Invalid configuration detected, maximal total duration can't be lower than zero");
                }
                if (configuration.ThresholdValue <= 0)
                {
                    throw new ArgumentNullException("Invalid configuration detected, threshold can't be negative or zero");
                }

                if (string.IsNullOrWhiteSpace(configuration.IoTHubEventHubEndpointConnectionString))
                {
                    throw new ArgumentNullException(nameof(configuration.IoTHubEventHubEndpointConnectionString));
                }
                if (string.IsNullOrWhiteSpace(configuration.StorageConnectionString))
                {
                    throw new ArgumentNullException(nameof(configuration.StorageConnectionString));
                }
                if (string.IsNullOrWhiteSpace(configuration.BlobContainerName))
                {
                    throw new ArgumentNullException(nameof(configuration.BlobContainerName));
                }
                if (string.IsNullOrWhiteSpace(configuration.EventHubConsumerGroup))
                {
                    throw new ArgumentNullException(nameof(configuration.EventHubConsumerGroup));
                }

                if (configuration.ExpectedMaximalDuration == 0)
                {
                    configuration.ExpectedMaximalDuration = uint.MaxValue;
                }

                _currentConfiguration = configuration;

                Interlocked.Exchange(ref _totalValueChangesCount, 0);

                _cancellationTokenSource = new CancellationTokenSource();

                //// Initialize EventProcessorWrapper
                if (_clientWrapper == null || _clientWrapper.GetHashCode() != EventProcessorWrapper.GetHashCode(_currentConfiguration))
                {
                    _clientWrapper = new EventProcessorWrapper(_currentConfiguration, _logger);
                    await _clientWrapper.InitializeClient(_cancellationTokenSource.Token).ConfigureAwait(false);
                }

                _clientWrapper.ProcessEventAsync += Client_ProcessEventAsync;
                await _clientWrapper.StartProcessingAsync(_cancellationTokenSource.Token).ConfigureAwait(false);

                _startTime = DateTime.UtcNow;

                // Initialize checkers.
                _missingTimestampsChecker = new MissingTimestampsChecker(
                    TimeSpan.FromMilliseconds(_currentConfiguration.ExpectedIntervalOfValueChanges),
                    TimeSpan.FromMilliseconds(_currentConfiguration.ThresholdValue),
                    _logger
                    );
                _missingTimestampsChecker.StartAsync(
                    TimeSpan.FromMilliseconds(kCheckerDelayMilliseconds),
                    _cancellationTokenSource.Token
                    ).Start();

                _messageProcessingDelayChecker = new MessageProcessingDelayChecker(
                    TimeSpan.FromMilliseconds(_currentConfiguration.ThresholdValue),
                    _logger
                    );

                _messageDeliveryDelayChecker = new MessageDeliveryDelayChecker(
                    TimeSpan.FromMilliseconds(_currentConfiguration.ExpectedMaximalDuration),
                    _logger
                    );

                _valueChangeCounterPerNodeId = new ValueChangeCounterPerNodeId(_logger);

                _missingValueChangesChecker = new MissingValueChangesChecker(
                    _currentConfiguration.ExpectedValueChangesPerTimestamp,
                    _logger
                    );
                _missingValueChangesChecker.StartAsync(
                    TimeSpan.FromMilliseconds(kCheckerDelayMilliseconds),
                    _cancellationTokenSource.Token
                    ).Start();

                _incrementalIntValueChecker = new IncrementalIntValueChecker(_logger);

                _incrementalSequenceChecker = new SequenceNumberChecker(_logger);

                _restartAnnouncementReceived = false;

                return(new StartResult());
            }
            finally {
                _logger.LogInformation("StartAsync finished in {elapsed}", sw.Elapsed);
            }
        }