internal int RegisterWorkItemGroup(string workItemGroupName, IGrainContext context, Func <string> statusGetter)
        {
            lock (lockable)
            {
                int i = workItemGroupCounter;
                workItemGroupCounter++;
                if (i == turnsExecutedPerWorkItemGroup.Length)
                {
                    // need to resize the array
                    Array.Resize(ref turnsExecutedPerWorkItemGroup, 2 * turnsExecutedPerWorkItemGroup.Length);
                    Array.Resize(ref workItemGroupStatuses, 2 * workItemGroupStatuses.Length);
                }
                CounterStorage storage = ReportPerWorkItemStats(context) ? CounterStorage.LogAndTable : CounterStorage.DontStore;
                turnsExecutedPerWorkItemGroup[i] = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.SCHEDULER_ACTIVATION_TURNSEXECUTED_PERACTIVATION, workItemGroupName), storage);
                workItemGroupStatuses[i]         = StringValueStatistic.FindOrCreate(new StatisticName(StatisticNames.SCHEDULER_ACTIVATION_STATUS_PERACTIVATION, workItemGroupName), statusGetter, storage);
                return(i);
            }

            bool ReportPerWorkItemStats(IGrainContext context)
            {
                return(context is ISystemTargetBase
                    ? this.collectionLevel >= StatisticsLevel.Verbose2
                    : this.collectionLevel >= StatisticsLevel.Verbose3);
            }
        }
Exemplo n.º 2
0
        public HttpResponseMessage GetCounterOverallTotal(string groupName, string counterName)
        {
            var verificationResult = VerifyGroupAndCounterName(groupName, counterName);

            if (verificationResult != null)
            {
                return(verificationResult);
            }

            CounterStorage.MetricsCounters.ClientRequests.Mark();
            using (var reader = CounterStorage.CreateReader())
            {
                try
                {
                    var overallTotal = reader.GetCounterTotal(groupName, counterName);
                    return(Request.CreateResponse(HttpStatusCode.OK, overallTotal));
                }
                catch (InvalidDataException e)
                {
                    if (e.Data.Contains("DoesntExist"))
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound, "Counter with specified group and name wasn't found"));
                    }

                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
                }
            }
        }
Exemplo n.º 3
0
        public HttpResponseMessage GetCounterOverallTotal(string groupName, string counterName)
        {
            var verificationResult = VerifyGroupAndCounterName(groupName, counterName);

            if (verificationResult != null)
            {
                return(verificationResult);
            }

            CounterStorage.MetricsCounters.ClientRequests.Mark();
            using (var reader = CounterStorage.CreateReader())
            {
                try
                {
                    long?total;
                    if (!reader.TryGetCounterTotal(groupName, counterName, out total))
                    {
                        return(GetMessageWithObject(new CounterTotal {
                            IsExists = false
                        }, HttpStatusCode.NotFound));
                    }

                    Debug.Assert(total.HasValue);
                    return(GetMessageWithObject(new CounterTotal {
                        IsExists = true, Total = total.Value
                    }));
                }
                catch (Exception e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
                }
            }
        }
        internal static void Init(TimeSpan responseTimeout)
        {
            if (!StatisticsCollector.CollectApplicationRequestsStats)
            {
                return;
            }

            const CounterStorage storage = CounterStorage.LogAndTable;

            appRequestsLatencyHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram_ForTiming(
                StatisticNames.APP_REQUESTS_LATENCY_HISTOGRAM, NUM_APP_REQUESTS_EXP_LATENCY_HISTOGRAM_CATEGORIES);

            timedOutRequests        = CounterStatistic.FindOrCreate(StatisticNames.APP_REQUESTS_TIMED_OUT, storage);
            totalAppRequests        = CounterStatistic.FindOrCreate(StatisticNames.APP_REQUESTS_TOTAL_NUMBER_OF_REQUESTS, storage);
            appRequestsTotalLatency = CounterStatistic.FindOrCreate(StatisticNames.APP_REQUESTS_LATENCY_TOTAL, false, storage, true);

            appRequestsAverageLatency = FloatValueStatistic.FindOrCreate(
                StatisticNames.APP_REQUESTS_LATENCY_AVERAGE,
                () =>
            {
                long totalLatencyInTicks = appRequestsTotalLatency.GetCurrentValue();
                if (totalLatencyInTicks == 0)
                {
                    return(0);
                }
                long numReqs = totalAppRequests.GetCurrentValue();
                long averageLatencyInTicks = (long)((double)totalLatencyInTicks / (double)numReqs);
                return((float)Utils.TicksToMilliSeconds(averageLatencyInTicks));
            }, storage);
        }
Exemplo n.º 5
0
        public HttpResponseMessage Delete(string groupName, string counterName)
        {
            var verificationResult = VerifyGroupAndCounterName(groupName, counterName);

            if (verificationResult != null)
            {
                return(verificationResult);
            }

            using (var writer = CounterStorage.CreateWriter())
            {
                writer.Delete(groupName, counterName);
                writer.Commit();
            }

            CounterStorage.MetricsCounters.ClientRequests.Mark();
            CounterStorage.MetricsCounters.Deletes.Mark();
            CounterStorage.Publisher.RaiseNotification(new ChangeNotification
            {
                GroupName   = groupName,
                CounterName = counterName,
                Action      = CounterChangeAction.Delete,
                Delta       = 0,
                Total       = 0
            });

            return(GetEmptyMessage(HttpStatusCode.NoContent));
        }
Exemplo n.º 6
0
        public BackupRestoreTests()
        {
            DeleteTempFolders();

            var uniqueId = Guid.NewGuid();

            BackupDestinationDirectory += uniqueId;
            BackupSourceDirectory      += uniqueId;
            RestoreToDirectory         += uniqueId;
            DocumentDatabaseDirectory  += uniqueId;

            config = new RavenConfiguration
            {
                Port                    = 8090,
                DataDirectory           = DocumentDatabaseDirectory,
                RunInMemory             = false,
                DefaultStorageTypeName  = "Voron",
                AnonymousUserAccessMode = AnonymousUserAccessMode.Admin,
                Encryption              = { UseFips = ConfigurationHelper.UseFipsEncryptionAlgorithms },
            };

            config.Counter.DataDirectory             = BackupSourceDirectory;
            config.Settings["Raven/StorageTypeName"] = config.DefaultStorageTypeName;
            config.PostInit();

            storage = new CounterStorage("http://localhost:8080", "TestCounter", config);
            storage.Environment.Options.IncrementalBackupEnabled = true;
        }
Exemplo n.º 7
0
 public CountersReplicationTopologyDiscoverer(CounterStorage counterStorage, RavenJArray @from, int ttl, ILog log)
 {
     this.counterStorage = counterStorage;
     this.ttl            = ttl;
     this.log            = log;
     this.@from          = @from;
     requestFactory      = new HttpRavenRequestFactory();
 }
 public HttpResponseMessage GetLastEtag(Guid serverId)
 {
     using (var reader = CounterStorage.CreateReader())
     {
         var lastEtag = reader.GetLastEtagFor(serverId);
         return(Request.CreateResponse(HttpStatusCode.OK, lastEtag));
     }
 }
Exemplo n.º 9
0
 private void StoreCounterChange(long change, CounterStorage counterStorage)
 {
     using (var writer = counterStorage.CreateWriter())
     {
         writer.Store("Bar", "Foo", change);
         writer.Commit();
     }
 }
Exemplo n.º 10
0
 public HttpResponseMessage GetCounterGroups(int skip, int take)
 {
     using (var reader = CounterStorage.CreateReader())
     {
         CounterStorage.MetricsCounters.ClientRequests.Mark();
         return(Request.CreateResponse(HttpStatusCode.OK, reader.GetCounterGroups(skip, take).ToList()));
     }
 }
Exemplo n.º 11
0
        public HttpResponseMessage GetCounterStatesSinceEtag(long etag, int skip, int take)
        {
            List <CounterState> deltas;

            using (var reader = CounterStorage.CreateReader())
                deltas = reader.GetCountersSinceEtag(etag + 1, skip, take).ToList();

            return(GetMessageWithObject(deltas));
        }
Exemplo n.º 12
0
        protected CounterStorage NewCounterStorage()
        {
            var newCounterStorage = new CounterStorage(String.Empty, DefaultCounterStorageName, new InMemoryRavenConfiguration
            {
                RunInMemory = true
            });

            disposables.Add(newCounterStorage);
            return(newCounterStorage);
        }
Exemplo n.º 13
0
        public override async Task <HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
        {
            if (ForceClusterAwareness == false)
            {
                var  clusterAwareHeader = GetClusterHeader(controllerContext, Constants.Cluster.ClusterAwareHeader);
                bool clusterAware;
                if (clusterAwareHeader == null || bool.TryParse(clusterAwareHeader, out clusterAware) == false || clusterAware == false)
                {
                    return(await base.ExecuteAsync(controllerContext, cancellationToken).ConfigureAwait(false));
                }
            }

            InnerInitialization(controllerContext);

            if (CounterStorage == null || ClusterManager.IsActive() == false)
            {
                return(await base.ExecuteAsync(controllerContext, cancellationToken).ConfigureAwait(false));
            }

            if (CountersName != null && await CountersLandlord.GetResourceInternal(CountersName).ConfigureAwait(false) == null)
            {
                var msg = "Could not find a counter named: " + CountersName;
                return(GetMessageWithObject(new { Error = msg }, HttpStatusCode.ServiceUnavailable));
            }

            if (CounterStorage.IsClusterDatabase() == false)
            {
                return(await base.ExecuteAsync(controllerContext, cancellationToken).ConfigureAwait(false));
            }

            if (ClusterManager.IsLeader())
            {
                return(await base.ExecuteAsync(controllerContext, cancellationToken).ConfigureAwait(false));
            }

            if (IsReadRequest(controllerContext))
            {
                var clusterReadBehaviorHeader = GetClusterHeader(controllerContext, Constants.Cluster.ClusterReadBehaviorHeader);
                if (string.Equals(clusterReadBehaviorHeader, "All", StringComparison.OrdinalIgnoreCase))
                {
                    return(await base.ExecuteAsync(controllerContext, cancellationToken).ConfigureAwait(false));
                }
            }

            var  clusterFailoverBehaviorHeader = GetClusterHeader(controllerContext, Constants.Cluster.ClusterFailoverBehaviorHeader);
            bool clusterFailoverBehavior;

            if (bool.TryParse(clusterFailoverBehaviorHeader, out clusterFailoverBehavior) && clusterFailoverBehavior)
            {
                return(await base.ExecuteAsync(controllerContext, cancellationToken).ConfigureAwait(false));
            }

            return(RedirectToLeader(controllerContext.Request));
        }
Exemplo n.º 14
0
 private AverageTimeSpanStatistic(string name, CounterStorage storage)
 {
     Name         = name;
     IsValueDelta = false;
     Storage      = storage;
     // the following counters are used internally and shouldn't be stored. the derived value,
     // the average timespan, will be stored in 'storage'.
     tickAccum     = CounterStatistic.FindOrCreate(new StatisticName(name + ".tickAccum"), IsValueDelta, CounterStorage.DontStore);
     sampleCounter = CounterStatistic.FindOrCreate(new StatisticName(name + ".sampleCounter"), IsValueDelta, CounterStorage.DontStore);
     instanceLock  = new object();
 }
Exemplo n.º 15
0
 // Must be called while Lockable is locked
 private CounterStatistic(string name, bool useDelta, CounterStorage storage, bool isHidden)
 {
     Name             = name;
     UseDelta         = useDelta;
     Storage          = storage;
     last             = 0;
     firstStatDisplay = true;
     valueConverter   = null;
     value            = 0;
     this.isHidden    = isHidden;
 }
Exemplo n.º 16
0
 ThrowIfNotConsistent(
     AverageTimeSpanStatistic expected,
     StatisticName name,
     CounterStorage storage)
 {
     if (storage != expected.Storage)
     {
         throw new ArgumentException(
                   $"Please verity that all invocations of AverageTimeSpanStatistic.FindOrCreate() for instance \"{name.Name}\" all specify the same storage type {Enum.GetName(typeof(CounterStorage), expected.Storage)}",
                   nameof(storage));
     }
 }
 private static void SetupCounters(CounterStorage counterStorage)
 {
     using (var writer = counterStorage.CreateWriter())
     {
         writer.Store("ga", "ca", 0);
         writer.Store("ga", "cb", 1);
         writer.Store("ga", "cc", 2);
         writer.Store("gb", "cb", 2);
         writer.Store("gc", "cc", 3);
         writer.Commit();
     }
 }
        public async Task <HttpResponseMessage> ReplicationsSave()
        {
            var newReplicationDocument = await ReadJsonObjectAsync <CountersReplicationDocument>().ConfigureAwait(false);

            using (var writer = CounterStorage.CreateWriter())
            {
                writer.UpdateReplications(newReplicationDocument);
                writer.Commit();

                return(GetEmptyMessage());
            }
        }
Exemplo n.º 19
0
 // Must be called while Lockable is locked
 private CounterStatistic(string name, bool useDelta, CounterStorage storage, bool isHidden)
 {
     Name                     = name;
     UseDelta                 = useDelta;
     Storage                  = storage;
     id                       = Interlocked.Increment(ref nextId);
     last                     = 0;
     firstStatDisplay         = true;
     valueConverter           = null;
     nonOrleansThreadsCounter = 0;
     this.isHidden            = isHidden;
 }
        public HttpResponseMessage ReplicationsGet()
        {
            using (var reader = CounterStorage.CreateReader())
            {
                var replicationData = reader.GetReplicationData();

                if (replicationData == null || replicationData.Destinations.Count == 0)
                {
                    return(GetEmptyMessage(HttpStatusCode.NotFound));
                }
                return(GetMessageWithObject(replicationData));
            }
        }
Exemplo n.º 21
0
 // Must be called while Lockable is locked
 private CounterStatistic(string name, bool useDelta, CounterStorage storage, bool isHidden)
 {
     Name                            = name;
     UseDelta                        = useDelta;
     Storage                         = storage;
     id                              = Interlocked.Increment(ref nextId);
     last                            = 0;
     firstStatDisplay                = true;
     valueConverter                  = null;
     nonOrleansThreadsCounter        = 0;
     this.isHidden                   = isHidden;
     specificStatisticFromAllThreads = new ConcurrentStack <ReferenceLong>();
 }
Exemplo n.º 22
0
        public BackupOperation(CounterStorage storage, string backupSourceDirectory, string backupDestinationDirectory, StorageEnvironment env, bool incrementalBackup, CounterStorageDocument counterDocument)
        {
            this.storage = storage;
            this.backupDestinationDirectory = backupDestinationDirectory;
            this.env = env;
            this.incrementalBackup     = incrementalBackup;
            this.counterDocument       = counterDocument;
            this.backupSourceDirectory = backupSourceDirectory;
            backupFilename             = counterDocument.Id + ".Voron.Backup";

            if (incrementalBackup)
            {
                PrepareForIncrementalBackup();
            }
        }
Exemplo n.º 23
0
        public HttpResponseMessage GetCounter(string groupName, string counterName)
        {
            var verificationResult = VerifyGroupAndCounterName(groupName, counterName);

            if (verificationResult != null)
            {
                return(verificationResult);
            }

            CounterStorage.MetricsCounters.ClientRequests.Mark();
            using (var reader = CounterStorage.CreateReader())
            {
                var result = reader.GetCounter(groupName, counterName);
                return(GetMessageWithObject(result));
            }
        }
Exemplo n.º 24
0
 internal static int RegisterWorkItemGroup(string workItemGroupName, ISchedulingContext context, Func <string> statusGetter)
 {
     lock (lockable)
     {
         int i = workItemGroupCounter;
         workItemGroupCounter++;
         if (i == turnsExecutedPerWorkItemGroup.Length)
         {
             // need to resize the array
             Array.Resize(ref turnsExecutedPerWorkItemGroup, 2 * turnsExecutedPerWorkItemGroup.Length);
             Array.Resize(ref workItemGroupStatuses, 2 * workItemGroupStatuses.Length);
         }
         CounterStorage storage = StatisticsCollector.ReportPerWorkItemStats(context) ? CounterStorage.LogAndTable : CounterStorage.DontStore;
         turnsExecutedPerWorkItemGroup[i] = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.SCHEDULER_ACTIVATION_TURNSEXECUTED_PERACTIVATION, workItemGroupName), storage);
         workItemGroupStatuses[i]         = StringValueStatistic.FindOrCreate(new StatisticName(StatisticNames.SCHEDULER_ACTIVATION_STATUS_PERACTIVATION, workItemGroupName), statusGetter, storage);
         return(i);
     }
 }
Exemplo n.º 25
0
        public SerializationStatisticsGroup(IOptions <StatisticsOptions> statisticsOptions)
        {
            this.CollectSerializationStats = statisticsOptions.Value.CollectionLevel >= StatisticsLevel.Verbose;
            if (this.CollectSerializationStats)
            {
                const CounterStorage store = CounterStorage.LogOnly;
                Copies                 = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_DEEPCOPIES, store);
                Serializations         = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_SERIALIZATION, store);
                Deserializations       = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_DESERIALIZATION, store);
                HeaderSers             = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_HEADER_SERIALIZATION, store);
                HeaderDesers           = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_HEADER_DESERIALIZATION, store);
                HeaderSersNumHeaders   = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_HEADER_SERIALIZATION_NUMHEADERS, store);
                HeaderDesersNumHeaders = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_HEADER_DESERIALIZATION_NUMHEADERS, store);
                CopyTimeStatistic      = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_DEEPCOPY_MILLIS, store).AddValueConverter(Utils.TicksToMilliSeconds);
                SerTimeStatistic       = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_SERIALIZATION_MILLIS, store).AddValueConverter(Utils.TicksToMilliSeconds);
                DeserTimeStatistic     = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_DESERIALIZATION_MILLIS, store).AddValueConverter(Utils.TicksToMilliSeconds);
                HeaderSerTime          = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_HEADER_SERIALIZATION_MILLIS, store).AddValueConverter(Utils.TicksToMilliSeconds);
                HeaderDeserTime        = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_HEADER_DESERIALIZATION_MILLIS, store).AddValueConverter(Utils.TicksToMilliSeconds);

                TotalTimeInSerializer = IntValueStatistic.FindOrCreate(
                    StatisticNames.SERIALIZATION_TOTAL_TIME_IN_SERIALIZER_MILLIS,
                    () =>
                {
                    long ticks = CopyTimeStatistic.GetCurrentValue() +
                                 SerTimeStatistic.GetCurrentValue() +
                                 DeserTimeStatistic.GetCurrentValue() +
                                 HeaderSerTime.GetCurrentValue() +
                                 HeaderDeserTime.GetCurrentValue();
                    return(Utils.TicksToMilliSeconds(ticks));
                },
                    CounterStorage.LogAndTable);

                const CounterStorage storeFallback = CounterStorage.LogOnly;
                FallbackSerializations   = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_SERIALIZATION, storeFallback);
                FallbackDeserializations = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_DESERIALIZATION, storeFallback);
                FallbackCopies           = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_DEEPCOPIES, storeFallback);
                FallbackSerTimeStatistic = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_SERIALIZATION_MILLIS, storeFallback)
                                           .AddValueConverter(Utils.TicksToMilliSeconds);
                FallbackDeserTimeStatistic = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_DESERIALIZATION_MILLIS, storeFallback)
                                             .AddValueConverter(Utils.TicksToMilliSeconds);
                FallbackCopiesTimeStatistic = CounterStatistic.FindOrCreate(StatisticNames.SERIALIZATION_BODY_FALLBACK_DEEPCOPY_MILLIS, storeFallback)
                                              .AddValueConverter(Utils.TicksToMilliSeconds);
            }
        }
Exemplo n.º 26
0
        public QueueTrackingStatistic(string queueName)
        {
            if (StatisticsCollector.CollectQueueStats)
            {
                const CounterStorage storage = CounterStorage.LogAndTable;
                averageQueueSizeCounter = AverageValueStatistic.FindOrCreate(
                    new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, queueName), storage);
                numEnqueuedRequestsCounter = CounterStatistic.FindOrCreate(
                    new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, queueName), false, storage);

                if (TrackExtraStats)
                {
                    totalExecutionTime = TimeIntervalFactory.CreateTimeInterval(true);
                    averageArrivalRate = FloatValueStatistic.FindOrCreate(
                        new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, queueName),
                        () =>
                    {
                        TimeSpan totalTime = totalExecutionTime.Elapsed;
                        if (totalTime.Ticks == 0)
                        {
                            return(0);
                        }
                        long numReqs = numEnqueuedRequestsCounter.GetCurrentValue();
                        return((float)((((double)numReqs * (double)TimeSpan.TicksPerSecond)) / (double)totalTime.Ticks));
                    }, storage);
                }

                averageTimeInQueue = AverageValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_TIME_IN_QUEUE_AVERAGE_MILLIS_PER_QUEUE, queueName), storage);
                averageTimeInQueue.AddValueConverter(Utils.AverageTicksToMilliSeconds);

                if (averageTimeInAllQueues == null)
                {
                    averageTimeInAllQueues = AverageValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_TIME_IN_QUEUE_AVERAGE_MILLIS_PER_QUEUE, "AllQueues"), storage);
                    averageTimeInAllQueues.AddValueConverter(Utils.AverageTicksToMilliSeconds);
                }
                if (totalTimeInAllQueues == null)
                {
                    totalTimeInAllQueues = CounterStatistic.FindOrCreate(
                        new StatisticName(StatisticNames.QUEUES_TIME_IN_QUEUE_TOTAL_MILLIS_PER_QUEUE, "AllQueues"), false, storage);
                    totalTimeInAllQueues.AddValueConverter(Utils.TicksToMilliSeconds);
                }
            }
        }
Exemplo n.º 27
0
        public void Incremental_backup_and_restore_should_work()
        {
            var backupOperation = NewBackupOperation(true);

            StoreCounterChange(5, storage);
            backupOperation.Execute();
            Thread.Sleep(100);
            StoreCounterChange(-2, storage);
            backupOperation.Execute();
            Thread.Sleep(100);
            StoreCounterChange(3, storage);
            backupOperation.Execute();

            var restoreOperation = NewRestoreOperation();

            restoreOperation.Execute();

            var restoreConfig = new RavenConfiguration
            {
                RunInMemory = false
            };

            restoreConfig.Counter.DataDirectory = RestoreToDirectory;

            using (var restoredStorage = new CounterStorage("http://localhost:8081", "RestoredCounter", restoreConfig))
            {
                using (var reader = restoredStorage.CreateReader())
                {
                    long?total;
                    Assert.True(reader.TryGetCounterTotal("Bar", "Foo", out total));
                    Assert.NotNull(total);
                    Assert.Equal(6, total.Value);

                    /*var counter = reader.GetCounterValuesByPrefix("Bar", "Foo");
                     * var counterValues = counter.CounterValues.ToArray();
                     *
                     * Assert.Equal(8, counterValues[0].Value);
                     * Assert.True(counterValues[0].IsPositive());
                     * Assert.Equal(2, counterValues[1].Value);
                     * Assert.False(counterValues[1].IsPositive());*/
                }
            }
        }
Exemplo n.º 28
0
        public HttpResponseMessage GetCounterSummariesByGroup(int skip, int take, string group)
        {
            if (skip < 0)
            {
                return(GetMessageWithString("Skip must be non-negative number", HttpStatusCode.BadRequest));
            }
            if (take <= 0)
            {
                return(GetMessageWithString("Take must be non-negative number", HttpStatusCode.BadRequest));
            }

            CounterStorage.MetricsCounters.ClientRequests.Mark();
            using (var reader = CounterStorage.CreateReader())
            {
                group = group ?? string.Empty;
                var counters = reader.GetCounterSummariesByGroup(group, skip, take);
                return(GetMessageWithObject(counters));
            }
        }
Exemplo n.º 29
0
        public HttpResponseMessage PurgeTombstones()
        {
            CounterStorage.MetricsCounters.ClientRequests.Mark();

            while (true)
            {
                using (var writer = CounterStorage.CreateWriter())
                {
                    if (writer.PurgeOutdatedTombstones() == false)
                    {
                        break;
                    }

                    writer.Commit();
                }
            }

            return(GetEmptyMessage());
        }
Exemplo n.º 30
0
        public HttpResponseMessage DeleteByGroup(string groupName)
        {
            groupName = groupName ?? string.Empty;
            var deletedCount = 0;

            while (true)
            {
                var changeNotifications = new List <ChangeNotification>();
                using (var writer = CounterStorage.CreateWriter())
                {
                    var countersDetails = writer.GetCountersDetails(groupName).Take(1024).ToList();
                    if (countersDetails.Count == 0)
                    {
                        break;
                    }

                    foreach (var c in countersDetails)
                    {
                        writer.DeleteCounterInternal(c.Group, c.Name);
                        changeNotifications.Add(new ChangeNotification
                        {
                            GroupName   = c.Group,
                            CounterName = c.Name,
                            Action      = CounterChangeAction.Delete,
                            Delta       = 0,
                            Total       = 0
                        });
                    }
                    writer.Commit();

                    deletedCount += changeNotifications.Count;
                }

                CounterStorage.MetricsCounters.ClientRequests.Mark();
                changeNotifications.ForEach(change =>
                {
                    CounterStorage.Publisher.RaiseNotification(change);
                    CounterStorage.MetricsCounters.Deletes.Mark();
                });
            }

            return(GetMessageWithObject(deletedCount));
        }
Exemplo n.º 31
0
        static private AverageValueStatistic FindOrCreate_Impl(StatisticName name, CounterStorage storage, bool multiThreaded)
        {
            AverageValueStatistic stat;
#if COLLECT_AVERAGE
            if (multiThreaded)
            {
                stat = new MultiThreadedAverageValueStatistic(name);
            }
            else
            {
                stat = new SingleThreadedAverageValueStatistic(name);
            }
            stat.average = FloatValueStatistic.FindOrCreate(name,
                      () => stat.GetAverageValue(), storage);
#else
            stat = new AverageValueStatistic(name);
#endif
            
            return stat;
        }
Exemplo n.º 32
0
 private static CounterStatistic FindCounter(ConcurrentDictionary<string, CounterStatistic> counters, StatisticName name, CounterStorage storage)
 {
     CounterStatistic stat;
     if (counters.TryGetValue(name.Name, out stat))
     {
         return stat;
     }
     stat = CounterStatistic.FindOrCreate(name, storage);
     counters.TryAdd(name.Name, stat);
     return stat;
 }
Exemplo n.º 33
0
 static public AverageValueStatistic FindOrCreate(StatisticName name, CounterStorage storage = CounterStorage.LogOnly)
 {
     return FindOrCreate_Impl(name, storage, true);
 }
		public RavenCounterReplication(CounterStorage storage)
		{
			this.storage = storage;
			this.storage.CounterUpdated += SignalCounterUpdate;
			cancellation = new CancellationTokenSource();
		}