Exemplo n.º 1
0
        /// <summary>
        /// report error on the provided Action
        /// </summary>
        /// <param name="parentAction"></param>
        /// <param name="errorName"></param>
        /// <param name="errorCode"></param>
        /// <param name="reason"></param>
        public void ReportError(Action parentAction, string errorName, int errorCode, string reason)
        {
            // if capture errors is off -> do nothing
            if (CapturingDisabled || !configuration.CaptureErrors)
            {
                return;
            }

            if (beaconConfiguration.DataCollectionLevel == DataCollectionLevel.OFF)
            {
                return;
            }

            StringBuilder eventBuilder = new StringBuilder();

            BuildBasicEventData(eventBuilder, EventType.ERROR, errorName);

            var timestamp = timingProvider.ProvideTimestampInMilliseconds();

            AddKeyValuePair(eventBuilder, BEACON_KEY_PARENT_ACTION_ID, parentAction.ID);
            AddKeyValuePair(eventBuilder, BEACON_KEY_START_SEQUENCE_NUMBER, NextSequenceNumber);
            AddKeyValuePair(eventBuilder, BEACON_KEY_TIME_0, GetTimeSinceBeaconCreation(timestamp));
            AddKeyValuePair(eventBuilder, BEACON_KEY_ERROR_CODE, errorCode);
            AddKeyValuePairIfValueIsNotNull(eventBuilder, BEACON_KEY_ERROR_REASON, reason);

            AddEventData(timestamp, eventBuilder);
        }
Exemplo n.º 2
0
        /// <summary>
        /// report error on the provided Action
        /// </summary>
        /// <param name="parentAction"></param>
        /// <param name="errorName"></param>
        /// <param name="errorCode"></param>
        /// <param name="reason"></param>
        public void ReportError(Action parentAction, string errorName, int errorCode, string reason)
        {
            // if capture errors is off -> do nothing
            if (CapturingDisabled || !configuration.CaptureErrors)
            {
                return;
            }

            if (beaconConfiguration.DataCollectionLevel == DataCollectionLevel.OFF)
            {
                return;
            }

            StringBuilder eventBuilder = new StringBuilder();

            BuildBasicEventData(eventBuilder, EventType.ERROR, errorName);

            var timestamp = timingProvider.ProvideTimestampInMilliseconds();

            AddKeyValuePair(eventBuilder, BeaconKeyParentActionID, parentAction.ID);
            AddKeyValuePair(eventBuilder, BeaconKeyStartSequenceNumber, NextSequenceNumber);
            AddKeyValuePair(eventBuilder, BeaconKeyTimeZero, GetTimeSinceBeaconCreation(timestamp));
            AddKeyValuePair(eventBuilder, BeaconKeyErrorCode, errorCode);
            AddKeyValuePairIfValueIsNotNull(eventBuilder, BeaconKeyErrorReason, reason);

            AddEventData(timestamp, eventBuilder);
        }
Exemplo n.º 3
0
        public void Setup()
        {
            currentTime      = 1;
            newSessions      = new List <SessionWrapper>();
            openSessions     = new List <SessionWrapper>();
            finishedSessions = new List <SessionWrapper>();

            // http client
            httpClient = Substitute.For <IHTTPClient>();

            // provider
            timingProvider = Substitute.For <ITimingProvider>();
            timingProvider.ProvideTimestampInMilliseconds().Returns(x => { return(++currentTime); }); // every access is a tick
            httpClientProvider = Substitute.For <IHTTPClientProvider>();
            httpClientProvider.CreateClient(Arg.Any <HTTPClientConfiguration>()).Returns(x => httpClient);

            // context
            context = Substitute.For <IBeaconSendingContext>();
            context.HTTPClientProvider.Returns(x => httpClientProvider);
            context.GetHTTPClient().Returns(x => httpClient);
            context.IsCaptureOn.Returns(true);

            // beacon sender
            logger       = Substitute.For <ILogger>();
            beaconSender = new BeaconSender(logger, config, httpClientProvider, timingProvider);

            // current time getter
            context.CurrentTimestamp.Returns(x => timingProvider.ProvideTimestampInMilliseconds());

            // sessions
            context.NewSessions.Returns(newSessions);
            context.OpenAndConfiguredSessions.Returns(openSessions);
            context.FinishedAndConfiguredSessions.Returns(finishedSessions);
        }
Exemplo n.º 4
0
        private int SplitTimedOutSessions()
        {
            var sleepTimeInMillis      = DefaultSleepTimeInMillis;
            var sessionProxiesToRemove = new List <ISessionProxy>();
            var allSessionProxies      = sessionsToSplitByTimeout.ToList();

            foreach (var sessionProxy in allSessionProxies)
            {
                var nextSessionSplitInMillis = sessionProxy.SplitSessionByTime();
                if (nextSessionSplitInMillis < 0)
                {
                    sessionProxiesToRemove.Add(sessionProxy);
                    continue;
                }

                var nowInMillis         = timingProvider.ProvideTimestampInMilliseconds();
                var durationToNextSplit = (int)(nextSessionSplitInMillis - nowInMillis);
                if (durationToNextSplit < 0)
                {
                    continue;
                }

                sleepTimeInMillis = Math.Min(sleepTimeInMillis, durationToNextSplit);
            }

            foreach (var sessionProxy in sessionProxiesToRemove)
            {
                sessionsToSplitByTimeout.Remove(sessionProxy);
            }

            return(sleepTimeInMillis);
        }
Exemplo n.º 5
0
        public void StartTimeIsSetInConstructor()
        {
            // given
            mockTimingProvider.ProvideTimestampInMilliseconds().Returns(1234L);
            var target = new Action(logger, beacon, "test", new SynchronizedQueue <IAction>());

            // then
            Assert.That(target.StartTime, Is.EqualTo(1234L));
        }
Exemplo n.º 6
0
        public void LeavingAParentActionWillLeaveAllOpenChildActionsFirst()
        {
            // given
            int startTimestamp = 100;

            mockTimingProvider.ProvideTimestampInMilliseconds().Returns(x =>
            {
                startTimestamp += 1;
                return(startTimestamp);
            });
            var target = new RootAction(logger, beacon, "root action", new SynchronizedQueue <IAction>());

            var childActionOne = target.EnterAction("child one");
            var childActionTwo = target.EnterAction("child two");

            // when leaving the parent action
            target.LeaveAction();

            // then
            Assert.That(target.IsActionLeft, Is.True);
            Assert.That(((Action)childActionOne).IsActionLeft, Is.True);
            Assert.That(((Action)childActionTwo).IsActionLeft, Is.True);

            Assert.That(((Action)childActionTwo).EndTime, Is.EqualTo(((Action)childActionOne).EndTime + 2));
            Assert.That(target.EndTime, Is.EqualTo(((Action)childActionTwo).EndTime + 1));
        }
Exemplo n.º 7
0
        // *** constructor ***

        /// <summary>
        /// Creates a new instance of type Beacon
        /// </summary>
        /// <param name="logger">Logger for logging messages</param>
        /// <param name="cache">Cache storing beacon related data</param>
        /// <param name="configuration">OpenKit related configuration</param>
        /// <param name="clientIPAddress">The client's IP address</param>
        /// <param name="threadIdProvider">Provider for retrieving thread id</param>
        /// <param name="timingProvider">Provider for time related methods</param>
        public Beacon(ILogger logger, BeaconCache beaconCache, OpenKitConfiguration configuration, string clientIPAddress,
                      IThreadIDProvider threadIDProvider, ITimingProvider timingProvider)
        {
            this.logger         = logger;
            this.beaconCache    = beaconCache;
            this.sessionNumber  = configuration.NextSessionNumber;
            this.timingProvider = timingProvider;

            this.configuration    = configuration;
            this.threadIDProvider = threadIDProvider;
            this.sessionStartTime = timingProvider.ProvideTimestampInMilliseconds();

            if (InetAddressValidator.IsValidIP(clientIPAddress))
            {
                this.clientIPAddress = clientIPAddress;
            }
            else
            {
                this.clientIPAddress = string.Empty;
            }

            // store the current http configuration
            this.httpConfiguration = configuration.HTTPClientConfig;

            basicBeaconData = CreateBasicBeaconData();
        }
Exemplo n.º 8
0
        public void Setup()
        {
            currentTime      = 1;
            lastTimeSyncTime = 1;
            newSessions      = new List <SessionWrapper>();
            openSessions     = new List <SessionWrapper>();
            finishedSessions = new List <SessionWrapper>();

            // http client
            httpClient = Substitute.For <IHTTPClient>();

            // provider
            timingProvider = Substitute.For <ITimingProvider>();
            timingProvider.ProvideTimestampInMilliseconds().Returns(x => { return(++currentTime); }); // every access is a tick
            httpClientProvider = Substitute.For <IHTTPClientProvider>();
            httpClientProvider.CreateClient(Arg.Any <HTTPClientConfiguration>()).Returns(x => httpClient);

            // context
            context = Substitute.For <IBeaconSendingContext>();
            context.HTTPClientProvider.Returns(x => httpClientProvider);
            context.GetHTTPClient().Returns(x => httpClient);
            context.LastTimeSyncTime.Returns(x => currentTime); // always return the current time to prevent re-sync
            context.IsCaptureOn.Returns(true);

            // beacon sender
            var logger = Substitute.For <ILogger>();

            beaconSender = new BeaconSender(logger, config, httpClientProvider, timingProvider);

            // return true by default
            context.IsTimeSyncSupported.Returns(true);

            // current time getter
            context.CurrentTimestamp.Returns(x => timingProvider.ProvideTimestampInMilliseconds());

            // last time sycn getter + setter
            context.LastTimeSyncTime = Arg.Do <long>(x => lastTimeSyncTime = x);
            context.LastTimeSyncTime = lastTimeSyncTime;

            // sessions
            context.NewSessions.Returns(newSessions);
            context.OpenAndConfiguredSessions.Returns(openSessions);
            context.FinishedAndConfiguredSessions.Returns(finishedSessions);
        }
Exemplo n.º 9
0
        public long SplitSessionByTime()
        {
            lock (lockObject)
            {
                if (IsFinished)
                {
                    return(-1);
                }

                var nextSplitTime = CalculateNextSplitTime();
                var now           = timingProvider.ProvideTimestampInMilliseconds();
                if (nextSplitTime < 0 || now < nextSplitTime)
                {
                    return(nextSplitTime);
                }

                SplitAndCreateNewInitialSession();

                return(CalculateNextSplitTime());
            }
        }
Exemplo n.º 10
0
        public void ShouldRunGivesFalseIfLastRunIsLessThanMaxAgeMillisecondsAgo()
        {
            // given
            var configuration = new BeaconCacheConfiguration(1000L, 1000L, 2000L);
            var target        = new TimeEvictionStrategy(mockLogger, mockBeaconCache, configuration, mockTimingProvider, isShutdownFunc)
            {
                LastRunTimestamp = 1000
            };

            mockTimingProvider.ProvideTimestampInMilliseconds().Returns(target.LastRunTimestamp + configuration.MaxRecordAge - 1);

            // then
            Assert.That(target.ShouldRun, Is.False);
        }
Exemplo n.º 11
0
        public void ShouldRunGivesFalseIfLastRunIsLessThanMaxAgeMillisecondsAgo()
        {
            // given
            var configuration = MockBeaconCacheConfig(1000L, 1000L, 2000L);
            var target        = CreateTimeEvictionStrategyWith(configuration);

            target.LastRunTimestamp = 1000;

            mockTimingProvider.ProvideTimestampInMilliseconds()
            .Returns(target.LastRunTimestamp + configuration.MaxRecordAge - 1);

            // then
            Assert.That(target.ShouldRun, Is.False);
        }
        public void CanGetCurrentTimestamp()
        {
            var expected = 12356789;

            timingProvider.ProvideTimestampInMilliseconds().Returns(expected);

            var target = new BeaconSendingContext(config, clientProvider, timingProvider);

            var actual = target.CurrentTimestamp;

            Assert.AreEqual(expected, actual);
            timingProvider.Received(1).ProvideTimestampInMilliseconds();
        }
Exemplo n.º 13
0
        public void Execute()
        {
            if (IsStrategyDisabled)
            {
                if (!infoShown && logger.IsInfoEnabled)
                {
                    logger.Info(GetType().Name + " strategy is disabled");
                    // suppress any further log output
                    infoShown = true;
                }
                return;
            }

            if (LastRunTimestamp < 0)
            {
                // first time execution
                LastRunTimestamp = timingProvider.ProvideTimestampInMilliseconds();
            }

            if (ShouldRun)
            {
                DoExecute();
            }
        }
Exemplo n.º 14
0
        public void EndingASessionEndsOpenRootActionsFirst()
        {
            // given
            int timestamp = 100;

            mockTimingProvider.ProvideTimestampInMilliseconds().Returns(x =>
            {
                timestamp++;
                return(timestamp);
            });

            var target        = new Session(logger, beaconSender, beacon);
            var rootActionOne = target.EnterAction("Root Action One");
            var rootActionTwo = target.EnterAction("Root Action Two");

            // when
            target.End();

            // then
            Assert.That(((RootAction)rootActionOne).IsActionLeft, Is.True);
            Assert.That(((RootAction)rootActionTwo).IsActionLeft, Is.True);
            Assert.That(((RootAction)rootActionOne).EndTime, Is.LessThan(((RootAction)rootActionTwo).EndTime));
            Assert.That(((RootAction)rootActionTwo).EndTime, Is.LessThan(target.EndTime));
        }
        public void CurrentTimeStampGet()
        {
            // given
            const long expected = 12356789;

            mockTimingProvider.ProvideTimestampInMilliseconds().Returns(expected);

            var target = CreateSendingContext().Build();

            Assert.That(mockTimingProvider.ReceivedCalls(), Is.Empty);

            // when
            var obtained = target.CurrentTimestamp;

            // then
            Assert.That(obtained, Is.EqualTo(expected));
            mockTimingProvider.Received(1).ProvideTimestampInMilliseconds();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a new instance of type Beacon
        /// </summary>
        /// <param name="initializer">provider of relevant parameters to initialize / create the beacon</param>
        /// <param name="configuration">OpenKit related configuration</param>
        internal Beacon(IBeaconInitializer initializer, IBeaconConfiguration configuration)
        {
            beaconCache = initializer.BeaconCache;

            var beaconId = initializer.SessionIdProvider.GetNextSessionId();

            SessionSequenceNumber = initializer.SessionSequenceNumber;
            beaconKey             = new BeaconKey(beaconId, SessionSequenceNumber);
            SessionNumber         = DetermineSessionNumber(configuration, beaconId);

            this.configuration = configuration;
            threadIdProvider   = initializer.ThreadIdProvider;
            timingProvider     = initializer.TimingProvider;
            SessionStartTime   = timingProvider.ProvideTimestampInMilliseconds();

            DeviceId = CreateDeviceId(configuration, initializer.RandomNumberGenerator);

            TrafficControlValue = initializer.RandomNumberGenerator.NextPercentageValue();

            logger = initializer.Logger;
            var ipAddress = initializer.ClientIpAddress;

            if (ipAddress == null)
            {
                // A client IP address, which is a null, is valid.
                // The real IP address is determined on the server side.
                clientIpAddress = null;
            }
            else if (InetAddressValidator.IsValidIP(ipAddress))
            {
                clientIpAddress = ipAddress;
            }
            else
            {
                if (logger.IsWarnEnabled)
                {
                    logger.Warn($"Beacon: Client IP address validation failed: {ipAddress}");
                }
                clientIpAddress = null; // determined on server side, based on remote IP address
            }

            basicBeaconData = CreateBasicBeaconData();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Creates a new instance of type Beacon
        /// </summary>
        /// <param name="logger">Logger for logging messages</param>
        /// <param name="cache">Cache storing beacon related data</param>
        /// <param name="configuration">OpenKit related configuration</param>
        /// <param name="clientIPAddress">The client's IP address</param>
        /// <param name="threadIdProvider">Provider for retrieving thread id</param>
        /// <param name="timingProvider">Provider for time related methods</param>
        /// <param name="randomNumberGenerator">Random number generator</param>
        internal Beacon(ILogger logger, BeaconCache beaconCache, OpenKitConfiguration configuration, string clientIPAddress,
                        IThreadIDProvider threadIDProvider, ITimingProvider timingProvider, IPRNGenerator randomNumberGenerator)
        {
            this.logger         = logger;
            this.beaconCache    = beaconCache;
            BeaconConfiguration = configuration.BeaconConfig;

            if (beaconConfiguration.DataCollectionLevel == DataCollectionLevel.USER_BEHAVIOR)
            {
                SessionNumber = configuration.NextSessionNumber;
                DeviceID      = Truncate(configuration.DeviceID);
            }
            else
            {
                SessionNumber = 1;
                DeviceID      = randomNumberGenerator.NextLong(long.MaxValue)
                                .ToString(CultureInfo.InvariantCulture);
            }

            this.timingProvider = timingProvider;

            this.configuration         = configuration;
            this.threadIDProvider      = threadIDProvider;
            this.randomNumberGenerator = randomNumberGenerator;
            sessionStartTime           = timingProvider.ProvideTimestampInMilliseconds();

            if (InetAddressValidator.IsValidIP(clientIPAddress))
            {
                this.clientIPAddress = clientIPAddress;
            }
            else
            {
                this.clientIPAddress = string.Empty;
            }
            // store the current http configuration
            httpConfiguration = configuration.HTTPClientConfig;
            basicBeaconData   = CreateBasicBeaconData();
        }
Exemplo n.º 18
0
        public void CloseOrEnqueueForClosingSetsSplitByEventsGracePeriodEndTimeIfSessionCannotBeClosed()
        {
            // given
            const long timestamp   = 10;
            const int  gracePeriod = 5;

            mockTimingProvider.ProvideTimestampInMilliseconds().Returns(timestamp);
            mockSession.TryEnd().Returns(false);
            var target = CreateContext();
            ISessionWatchdogContext targetExplicit = target;

            // when
            targetExplicit.CloseOrEnqueueForClosing(mockSession, gracePeriod);

            // then
            mockSession.Received(1).SplitByEventsGracePeriodEndTimeInMillis = (timestamp + gracePeriod);
        }