public EventFlowSubject <EventData> CreateItem(IConfiguration configuration, IHealthReporter healthReporter)
        {
            var input = new EventFlowSubject <EventData>();

            input.Labels.Add(ApplicationInsightsInputFactory.ApplicationInsightsInputTag, null);
            return(input);
        }
Exemplo n.º 2
0
        public void SubjectDeliversData()
        {
            var subject = new EventFlowSubject <int>();
            var obs1    = new Mock <IObserver <int> >();
            var obs2    = new Mock <IObserver <int> >();

            var s1 = subject.Subscribe(obs1.Object);
            var s2 = subject.Subscribe(obs2.Object);

            subject.OnNext(7);
            s2.Dispose();
            subject.OnNext(8);
            subject.OnCompleted();
            subject.OnNext(9);
            subject.Dispose();
            subject.OnNext(10);

            obs1.Verify(o => o.OnNext(It.IsAny <int>()), Times.Exactly(2));
            obs1.Verify(o => o.OnNext(It.Is <int>(i => i == 7)), Times.Exactly(1));
            obs1.Verify(o => o.OnNext(It.Is <int>(i => i == 8)), Times.Exactly(1));
            obs1.Verify(o => o.OnCompleted(), Times.Exactly(1));
            obs1.Verify(o => o.OnError(It.IsAny <Exception>()), Times.Exactly(0));

            obs2.Verify(o => o.OnNext(It.IsAny <int>()), Times.Exactly(1));
            obs1.Verify(o => o.OnNext(It.Is <int>(i => i == 7)), Times.Exactly(1));
            obs1.Verify(o => o.OnCompleted(), Times.Exactly(1));
            obs1.Verify(o => o.OnError(It.IsAny <Exception>()), Times.Exactly(0));
        }
Exemplo n.º 3
0
 public LoggerInput(IHealthReporter healthReporter)
 {
     Validation.Requires.NotNull(healthReporter, nameof(healthReporter));
     this.healthReporter = healthReporter;
     this.subject        = new EventFlowSubject <EventData>();
     this.healthReporter.ReportHealthy($"{nameof(LoggerInput)} initialized.", TraceTag);
 }
Exemplo n.º 4
0
        /// <summary>
        /// Construct a <see cref="SerilogInput"/>.
        /// </summary>
        /// <param name="healthReporter">A health reporter through which the input can report errors.</param>
        public SerilogInput(IHealthReporter healthReporter)
        {
            Requires.NotNull(healthReporter, nameof(healthReporter));

            this.healthReporter = healthReporter;
            this.subject        = new EventFlowSubject <EventData>();
        }
        private void Initialize(PerformanceCounterInputConfiguration configuration, IHealthReporter healthReporter)
        {
            this.syncObject               = new object();
            this.subject                  = new EventFlowSubject <EventData>();
            this.healthReporter           = healthReporter;
            this.processInstanceNameCache = new ProcessInstanceNameCache();
            this.sampleInterval           = TimeSpan.FromMilliseconds(configuration.SampleIntervalMsec);
            var currentProcess = Process.GetCurrentProcess();

            this.currentProcessName = currentProcess.ProcessName;
            this.currentProcessId   = currentProcess.Id;

            // The CLR Process ID counter used for process ID to counter instance name mapping for CLR counters will not read correctly
            // until at least one garbage collection is performed, so we will force one now.
            // The listener is usually created during service startup so the GC should not take very long.
            GC.Collect();

            this.trackedPerformanceCounters = new List <TrackedPerformanceCounter>();

            foreach (var counterConfiguration in configuration.Counters)
            {
                if (!counterConfiguration.Validate())
                {
                    healthReporter.ReportProblem($"{nameof(PerformanceCounterInput)}: configuration for counter {counterConfiguration.CounterName} is invalid");
                }
                else
                {
                    this.trackedPerformanceCounters.Add(new TrackedPerformanceCounter(counterConfiguration));
                }
            }

            this.collectionTimer = new Timer(this.DoCollection, null, this.sampleInterval, TimeSpan.FromDays(1));
        }
Exemplo n.º 6
0
 private void Initialize(SerilogInputConfiguration inputConfiguration, IHealthReporter healthReporter)
 {
     this.healthReporter     = healthReporter;
     this.inputConfiguration = inputConfiguration;
     this.subject            = new EventFlowSubject <EventData>();
     this.valueSerializer    = this.inputConfiguration.UseSerilogDepthLevel ? (Func <LogEventPropertyValue, object>) this.ToRawValue : this.ToRawScalar;
 }
Exemplo n.º 7
0
 public void Dispose()
 {
     if (subject != null)
     {
         this.subject.Dispose();
         this.subject = null;
     }
 }
        private void Initialize(List <EventSourceConfiguration> eventSources, IHealthReporter healthReporter)
        {
            this.healthReporter = healthReporter;
            this.subject        = new EventFlowSubject <EventData>();

            if (eventSources.Count() == 0)
            {
                healthReporter.ReportWarning($"{nameof(EventSourceInput)}: no event sources configured, the input will not produce any data", EventFlowContextIdentifiers.Configuration);
            }

            var invalidConfigurationItems = new List <EventSourceConfiguration>();

            foreach (var eventSourceConfiguration in eventSources)
            {
                if (!eventSourceConfiguration.Validate())
                {
                    healthReporter.ReportProblem($"{nameof(EventSourceInput)}: configuration for one of the sources is invalid", EventFlowContextIdentifiers.Configuration);
                    invalidConfigurationItems.Add(eventSourceConfiguration);
                }
            }
            // eventSources is a collection created by us, so we can modify it as necessary
            eventSources.RemoveAll(config => invalidConfigurationItems.Contains(config));

            // Special case: because of .NET bug https://github.com/dotnet/coreclr/issues/14434, using Microsoft-ApplicationInsights-Data will result in infinite loop.
            // So we will disable it by default, unless there is explicit configuration for this EventSource
            bool hasConfigForAppInsightsDataSource = eventSources.Any(config =>
                                                                      AppInsightsDataEventSource.Equals(config.ProviderName, StringComparison.Ordinal) ||
                                                                      AppInsightsDataEventSource.Equals(config.DisabledProviderNamePrefix, StringComparison.Ordinal));

            if (!hasConfigForAppInsightsDataSource)
            {
                eventSources.Add(new EventSourceConfiguration()
                {
                    DisabledProviderNamePrefix = AppInsightsDataEventSource
                });
            }

            this.EventSources = eventSources;

            bool haveDisabledSources = this.EventSources.Any(config => !string.IsNullOrWhiteSpace(config.DisabledProviderNamePrefix));

            if (haveDisabledSources)
            {
                this.disabledSources    = new ConcurrentDictionary <string, bool>();
                this.OnEventWrittenImpl = BroadcastEventIfSourceNotDisabled;
            }
            else
            {
                this.OnEventWrittenImpl = BroadcastEvent;
            }

            // Make sure the constructor has run to completion before enabling any sources.
            this.initialization = Task.Run(() =>
            {
                this.constructed = true;
                EnableInitialSources();
            });
        }
Exemplo n.º 9
0
        public NLogInput(IHealthReporter healthReporter)
        {
            _healthReporter        = healthReporter;
            OptimizeBufferReuse    = true;
            IncludeEventProperties = true;
            Layout = "${message}";

            _eventFlowSubject = new EventFlowSubject <EventData>();
        }
Exemplo n.º 10
0
        private void Initialize(IReadOnlyCollection <EtwProviderConfiguration> providers, IHealthReporter healthReporter)
        {
            this.healthReporter = healthReporter;
            this.subject        = new EventFlowSubject <EventData>();
            this.isDisposed     = false;
            this.SessionFactory = () => new StandardTraceEventSession(healthReporter);

            this.Providers = providers;
            // The session is not started until Activate() is called.
        }
Exemplo n.º 11
0
        private void Initialize(TraceInputConfiguration traceInputConfiguration)
        {
            Debug.Assert(traceInputConfiguration != null);
            Debug.Assert(this.healthReporter != null);

            this.subject = new EventFlowSubject <EventData>();

            Filter = new EventTypeFilter(traceInputConfiguration.TraceLevel);
            Trace.Listeners.Add(this);
            this.healthReporter.ReportHealthy($"{nameof(TraceInput)} initialized.", TraceTag);
        }
Exemplo n.º 12
0
        public void SubjectCompletesImmediatelyAfterDisposed()
        {
            var subject = new EventFlowSubject <int>();
            var obs1    = new Mock <IObserver <int> >();

            subject.Dispose();
            var s1 = subject.Subscribe(obs1.Object);

            s1.Dispose(); // No exception

            obs1.Verify(o => o.OnNext(It.IsAny <int>()), Times.Exactly(0));
            obs1.Verify(o => o.OnCompleted(), Times.Exactly(1));
            obs1.Verify(o => o.OnError(It.IsAny <Exception>()), Times.Exactly(0));
        }
Exemplo n.º 13
0
        private void Initialize(
            IReadOnlyCollection <EtwProviderConfiguration> providers,
            string sessionNamePrefix,
            bool cleanupOldSessions,
            bool restartExisting,
            IHealthReporter healthReporter)
        {
            this.healthReporter = healthReporter;
            this.subject        = new EventFlowSubject <EventData>();
            this.isDisposed     = false;
            this.SessionFactory = () => new StandardTraceEventSession(sessionNamePrefix, cleanupOldSessions, restartExisting, healthReporter);

            this.Providers = providers;
            // The session is not started until Activate() is called.
        }
Exemplo n.º 14
0
        public DiagnosticSourceInput(IReadOnlyCollection <DiagnosticSourceConfiguration> sources, IHealthReporter healthReporter)
        {
            if (sources == null)
            {
                throw new ArgumentNullException(nameof(sources));
            }

            if (healthReporter == null)
            {
                throw new ArgumentNullException(nameof(healthReporter));
            }

            _subject              = new EventFlowSubject <EventData>();
            _listenerObserver     = new DiagnosticListenerObserver(sources, _subject, healthReporter);
            _listenerSubscription = DiagnosticListener.AllListeners.Subscribe(_listenerObserver);
        }
        private void Initialize(IReadOnlyCollection <EventSourceConfiguration> eventSources, IHealthReporter healthReporter)
        {
            this.healthReporter = healthReporter;
            this.subject        = new EventFlowSubject <EventData>();

            this.EventSources = eventSources;
            if (this.EventSources.Count() == 0)
            {
                healthReporter.ReportWarning($"{nameof(EventSourceInput)}: no event sources configured", nameof(EventSourceInput));
                return;
            }

            lock (this)  // See OnEventSourceCreated() for explanation why we are locking on 'this' here.
            {
                EnableInitialSources();
                this.constructed = true;
            }
        }
Exemplo n.º 16
0
        private void Initialize(Log4netConfiguration myLog4NetConfig, IHealthReporter myHealthReporter)
        {
            this.healthReporter             = myHealthReporter;
            this._log4NetInputConfiguration = myLog4NetConfig;
            this.subject = new EventFlowSubject <EventData>();

            //Can we determine if the repo exists without try/catch
            try
            {
                eventFlowRepo = (Hierarchy)LogManager.CreateRepository("EventFlowRepo");
                _log4NetInputConfiguration.Log4netLevel = eventFlowRepo.LevelMap[_log4NetInputConfiguration.LogLevel];
                BasicConfigurator.Configure(eventFlowRepo, this);
            }
            catch (LogException)
            {
                eventFlowRepo = (Hierarchy)LogManager.GetRepository("EventFlowRepo");
            }
        }
Exemplo n.º 17
0
        private void Initialize(IReadOnlyCollection <EventSourceConfiguration> eventSources, IHealthReporter healthReporter)
        {
            this.healthReporter = healthReporter;
            this.subject        = new EventFlowSubject <EventData>();

            this.EventSources = eventSources;
            if (this.EventSources.Count() == 0)
            {
                healthReporter.ReportWarning($"{nameof(EventSourceInput)}: no event sources configured", nameof(EventSourceInput));
            }

            // Make sure the constructor has run to completion before enabling any sources.
            this.initialization = Task.Run(() =>
            {
                this.constructed = true;
                EnableInitialSources();
            });
        }
Exemplo n.º 18
0
        private void Initialize(List <EventSourceConfiguration> eventSources, IHealthReporter healthReporter)
        {
            this.healthReporter = healthReporter;
            this.subject        = new EventFlowSubject <EventData>();

            if (eventSources.Count() == 0)
            {
                healthReporter.ReportWarning($"{nameof(EventSourceInput)}: no event sources configured", EventFlowContextIdentifiers.Configuration);
            }

            var invalidConfigurationItems = new List <EventSourceConfiguration>();

            foreach (var eventSourceConfiguration in eventSources)
            {
                if (!eventSourceConfiguration.Validate())
                {
                    healthReporter.ReportProblem($"{nameof(EventSourceInput)}: configuration for one of the sources is invalid", EventFlowContextIdentifiers.Configuration);
                    invalidConfigurationItems.Add(eventSourceConfiguration);
                }
            }
            // eventSources is a collection created by us, so we can modify it as necessary
            eventSources.RemoveAll(config => invalidConfigurationItems.Contains(config));
            this.EventSources = eventSources;

            bool haveDisabledSources = this.EventSources.Any(config => !string.IsNullOrWhiteSpace(config.DisabledProviderNamePrefix));

            if (haveDisabledSources)
            {
                this.disabledSources    = new ConcurrentDictionary <string, bool>();
                this.OnEventWrittenImpl = BroadcastEventIfSourceNotDisabled;
            }
            else
            {
                this.OnEventWrittenImpl = BroadcastEvent;
            }

            // Make sure the constructor has run to completion before enabling any sources.
            this.initialization = Task.Run(() =>
            {
                this.constructed = true;
                EnableInitialSources();
            });
        }
Exemplo n.º 19
0
        public async Task SubjectWaitsOnSlowObservers()
        {
            // Use shutdown timeout long enough to be "infinite" from the test standpoint,
            // but short enough for the test run to finish in reasonable time
            // in case something goes seriously wrong.
            var ShutdownTimeout = TimeSpan.FromMinutes(15);

            var subject  = new EventFlowSubject <int>(ShutdownTimeout);
            var observer = new SlowObserver <int>();

            subject.Subscribe(observer);

            var nextDataTask = Task.Run(() => subject.OnNext(0));

            Assert.True(observer.OnNextStartedEvent.WaitOne(TimeSpan.FromSeconds(5)), "Five seconds should be plenty to start the OnNext() task");
            var completionTask = Task.Run(() => subject.OnCompleted());

            await Task.WhenAll(nextDataTask, completionTask);

            Assert.True(observer.OnNextExitTimestamp != DateTime.MinValue, "OnNext() was never called!");
            Assert.True(observer.OnCompletedEntryTimestamp != DateTime.MinValue, "OnCompleted was never called");
            Assert.True(observer.OnCompletedEntryTimestamp >= observer.OnNextExitTimestamp, "OnCompleted() should not have been called when OnNext() was in progress");
        }
Exemplo n.º 20
0
 public UnitTestInput()
 {
     subject = new EventFlowSubject <EventData>();
 }