blob: a360e1f7b8b8965f6cae2ce4f1e01e0e5cdc136e [file] [log] [blame]
Darin Petkovf1e85e42010-06-10 15:59:53 -07001// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef METRICS_COUNTER_H_
6#define METRICS_COUNTER_H_
7
Ken Mixter4c5daa42010-08-26 18:35:06 -07008#include <string>
Ken Mixterccd84c02010-08-16 19:57:13 -07009#include <time.h>
10
Darin Petkovcd8c3172010-06-24 10:13:54 -070011#include <base/basictypes.h>
Chris Masone817016a2011-05-12 14:14:48 -070012#include <base/memory/scoped_ptr.h>
Darin Petkovf1e85e42010-06-10 15:59:53 -070013#include <gtest/gtest_prod.h> // for FRIEND_TEST
14
Ken Mixter4c5daa42010-08-26 18:35:06 -070015class MetricsLibraryInterface;
16
Darin Petkovf1e85e42010-06-10 15:59:53 -070017namespace chromeos_metrics {
18
Ken Mixterccd84c02010-08-16 19:57:13 -070019// Constants useful for frequency statistics.
20const int kSecondsPerDay = 60 * 60 * 24;
21const int kSecondsPerWeek = kSecondsPerDay * 7;
22
Darin Petkovf1e85e42010-06-10 15:59:53 -070023// TaggedCounter maintains a persistent storage (i.e., a file)
24// aggregation counter for a given tag (e.g., day, hour) that survives
25// system shutdowns, reboots and crashes, as well as daemon process
26// restarts. The counter object is initialized by pointing to the
27// persistent storage file and providing a callback used for reporting
28// aggregated data. The counter can then be updated with additional
29// event counts. The aggregated count is reported through the
30// callback when the counter is explicitly flushed or when data for a
31// new tag arrives.
Darin Petkovcd8c3172010-06-24 10:13:54 -070032//
33// The primary reason for using an interface is to allow easier unit
34// testing in clients through mocking thus avoiding file access and
35// callbacks. Of course, it also enables alternative implementations
36// of the counter with additional features.
Darin Petkovf1e85e42010-06-10 15:59:53 -070037class TaggedCounterInterface {
38 public:
39 // Callback type used for reporting aggregated or flushed data.
40 // Once this callback is invoked by the counter, the reported
Darin Petkov1bb904e2010-06-16 15:58:06 -070041 // aggregated data is discarded.
Darin Petkovf1e85e42010-06-10 15:59:53 -070042 //
43 // |handle| is the |reporter_handle| pointer passed through Init.
44 // |tag| is the tag associated with the aggregated count.
45 // |count| is aggregated count.
Darin Petkovcd8c3172010-06-24 10:13:54 -070046 typedef void (*Reporter)(void* handle, int32 tag, int32 count);
Darin Petkovf1e85e42010-06-10 15:59:53 -070047
48 virtual ~TaggedCounterInterface() {}
49
Darin Petkovf1e85e42010-06-10 15:59:53 -070050 // Adds |count| of events for the given |tag|. If there's an
51 // existing aggregated count for a different tag, it's reported
52 // through the reporter callback and discarded.
Darin Petkovcd8c3172010-06-24 10:13:54 -070053 virtual void Update(int32 tag, int32 count) = 0;
Darin Petkovf1e85e42010-06-10 15:59:53 -070054
55 // Reports the current aggregated count (if any) through the
56 // reporter callback and discards it.
57 virtual void Flush() = 0;
58};
59
60class TaggedCounter : public TaggedCounterInterface {
61 public:
62 TaggedCounter();
Ken Mixter4c5daa42010-08-26 18:35:06 -070063 virtual ~TaggedCounter();
64
65 // Initializes the counter by providing the persistent storage
66 // location |filename| and a |reporter| callback for reporting
67 // aggregated counts. |reporter_handle| is sent to the |reporter|
68 // along with the aggregated counts.
69 //
70 // NOTE: The assumption is that this object is the sole owner of the
71 // persistent storage file so no locking is currently implemented.
72 virtual void Init(const char* filename,
73 Reporter reporter, void* reporter_handle);
Darin Petkovf1e85e42010-06-10 15:59:53 -070074
75 // Implementation of interface methods.
Ken Mixter4c5daa42010-08-26 18:35:06 -070076 virtual void Update(int32 tag, int32 count);
77 virtual void Flush();
Darin Petkovf1e85e42010-06-10 15:59:53 -070078
79 private:
80 friend class RecordTest;
81 friend class TaggedCounterTest;
82 FRIEND_TEST(TaggedCounterTest, BadFileLocation);
83 FRIEND_TEST(TaggedCounterTest, Flush);
84 FRIEND_TEST(TaggedCounterTest, InitFromFile);
85 FRIEND_TEST(TaggedCounterTest, Update);
86
87 // The current tag/count record is cached by the counter object to
88 // avoid potentially unnecessary I/O. The cached record can be in
89 // one of the following states:
90 enum RecordState {
91 kRecordInvalid, // Invalid record, sync from persistent storage needed.
92 kRecordNull, // No current record, persistent storage synced.
93 kRecordNullDirty, // No current record, persistent storage is invalid.
94 kRecordValid, // Current record valid, persistent storage synced.
95 kRecordValidDirty // Current record valid, persistent storage is invalid.
96 };
97
98 // Defines the tag/count record. Objects of this class are synced
99 // with the persistent storage through binary reads/writes.
100 class Record {
101 public:
102 // Creates a new Record with |tag_| and |count_| reset to 0.
103 Record() : tag_(0), count_(0) {}
104
105 // Initializes with |tag| and |count|. If |count| is negative,
106 // |count_| is set to 0.
Darin Petkovcd8c3172010-06-24 10:13:54 -0700107 void Init(int32 tag, int32 count);
Darin Petkovf1e85e42010-06-10 15:59:53 -0700108
109 // Adds |count| to the current |count_|. Negative |count| is
110 // ignored. In case of positive overflow, |count_| is saturated to
Darin Petkovcd8c3172010-06-24 10:13:54 -0700111 // kint32max.
112 void Add(int32 count);
Darin Petkovf1e85e42010-06-10 15:59:53 -0700113
Darin Petkovcd8c3172010-06-24 10:13:54 -0700114 int32 tag() const { return tag_; }
115 int32 count() const { return count_; }
Darin Petkovf1e85e42010-06-10 15:59:53 -0700116
117 private:
Darin Petkovcd8c3172010-06-24 10:13:54 -0700118 int32 tag_;
119 int32 count_;
Darin Petkovf1e85e42010-06-10 15:59:53 -0700120 };
121
122 // Implementation of the Update and Flush methods. Goes through the
123 // necessary steps to read, report, update, and sync the aggregated
124 // record.
Darin Petkovcd8c3172010-06-24 10:13:54 -0700125 void UpdateInternal(int32 tag, int32 count, bool flush);
Darin Petkovf1e85e42010-06-10 15:59:53 -0700126
127 // If the current cached record is invalid, reads it from persistent
128 // storage specified through file descriptor |fd| and updates the
129 // cached record state to either null, or valid depending on the
130 // persistent storage contents.
131 void ReadRecord(int fd);
132
133 // If there's an existing valid record and either |flush| is true,
134 // or the new |tag| is different than the old one, reports the
135 // aggregated data through the reporter callback and resets the
136 // cached record.
Darin Petkovcd8c3172010-06-24 10:13:54 -0700137 void ReportRecord(int32 tag, bool flush);
Darin Petkovf1e85e42010-06-10 15:59:53 -0700138
139 // Updates the cached record given the new |tag| and |count|. This
140 // method expects either a null cached record, or a valid cached
Darin Petkov1bb904e2010-06-16 15:58:06 -0700141 // record with the same tag as |tag|. If |flush| is true, the method
142 // asserts that the cached record is null and returns.
Darin Petkovcd8c3172010-06-24 10:13:54 -0700143 void UpdateRecord(int32 tag, int32 count, bool flush);
Darin Petkovf1e85e42010-06-10 15:59:53 -0700144
145 // If the cached record state is dirty, updates the persistent
146 // storage specified through file descriptor |fd| and switches the
147 // record state to non-dirty.
148 void WriteRecord(int fd);
149
150 // Persistent storage file path.
Ken Mixter4c5daa42010-08-26 18:35:06 -0700151 std::string filename_;
Darin Petkovf1e85e42010-06-10 15:59:53 -0700152
153 // Aggregated data reporter callback and handle to pass-through.
154 Reporter reporter_;
155 void* reporter_handle_;
156
157 // Current cached aggregation record.
158 Record record_;
159
160 // Current cached aggregation record state.
161 RecordState record_state_;
162};
163
Ken Mixter4c5daa42010-08-26 18:35:06 -0700164// TaggedCounterReporter provides a TaggedCounterInterface which both
165// counts tagged events and reports them up through the metrics
166// library to UMA.
167class TaggedCounterReporter : public TaggedCounterInterface {
168 public:
169 TaggedCounterReporter();
170 virtual ~TaggedCounterReporter();
171
172 // Set the metrics library used by all TaggedCounterReporter
173 // instances. We assume there is only one metrics library
174 // shared amongst all reporters.
175 static void SetMetricsLibraryInterface(MetricsLibraryInterface* metrics_lib) {
176 metrics_lib_ = metrics_lib;
177 }
178
179 // Initializes the counter by providing the persistent storage
180 // location |filename|, a |histogram_name| (a linear histogram) to
181 // report to with |min|, |max|, and |buckets| attributes for the
182 // histogram.
183 virtual void Init(const char* filename,
184 const char* histogram_name,
185 int min,
186 int max,
187 int buckets);
188
189 // Implementation of interface method.
190 virtual void Update(int32 tag, int32 count) {
191 tagged_counter_->Update(tag, count);
192 }
193 // Implementation of interface method.
194 virtual void Flush() {
195 tagged_counter_->Flush();
196 }
197
198 // Accessor functions.
199 const std::string& histogram_name() const {
200 return histogram_name_;
201 }
202
203 int min() const {
204 return min_;
205 }
206
207 int max() const {
208 return max_;
209 }
210
211 int buckets() const {
212 return buckets_;
213 }
214
215 protected:
216 friend class TaggedCounterReporterTest;
217 FRIEND_TEST(TaggedCounterReporterTest, Report);
218
219 static void Report(void* handle, int32 tag, int32 count);
220
221 static MetricsLibraryInterface* metrics_lib_;
222 scoped_ptr<TaggedCounter> tagged_counter_;
223 std::string histogram_name_;
224 int min_;
225 int max_;
226 int buckets_;
227};
228
Ken Mixterccd84c02010-08-16 19:57:13 -0700229// FrequencyCounter uses TaggedCounter to maintain a persistent
230// storage of the number of events that occur in a given cycle
231// duration (in other words, a frequency count). For example, to
232// count the number of blips per day, initialize |cycle_duration| to
233// chromeos_metrics::kSecondsPerDay, and call Update with the number
234// of blips that happen concurrently (usually 1). Reporting of the
235// value is done through TaggedCounter's reporter function.
236class FrequencyCounter {
237 public:
238 // Create a new frequency counter.
239 FrequencyCounter();
240 virtual ~FrequencyCounter();
241
Ken Mixter4c5daa42010-08-26 18:35:06 -0700242 // Initialize a frequency counter, which is necessary before first
243 // use. |tagged_counter| is used to store the counts, its memory
244 // will be managed by this FrequencyCounter. |cycle_duration| is
245 // the number of seconds in a cycle.
246 virtual void Init(TaggedCounterInterface* tagged_counter,
Ken Mixterccd84c02010-08-16 19:57:13 -0700247 time_t cycle_duration);
248 // Record that an event occurred. |count| is the number of concurrent
249 // events that have occurred. The time is implicitly assumed to be the
250 // time of the call.
251 virtual void Update(int32 count) {
252 UpdateInternal(count, time(NULL));
253 }
254
Ken Mixter4c5daa42010-08-26 18:35:06 -0700255 // Update the frequency counter based on the current time. If a
256 // cycle has finished, this will have the effect of flushing the
257 // cycle's count, without first requiring another update to the
258 // frequency counter. The more often this is called, the lower the
259 // latency to have a new sample submitted.
260 virtual void FlushFinishedCycles() {
261 Update(0);
262 }
263
264 // Accessor function.
265 const TaggedCounterInterface& tagged_counter() const {
266 return *tagged_counter_;
267 }
268
269 time_t cycle_duration() const {
270 return cycle_duration_;
271 }
272
Ken Mixterccd84c02010-08-16 19:57:13 -0700273 private:
274 friend class FrequencyCounterTest;
275 FRIEND_TEST(FrequencyCounterTest, UpdateInternal);
Ken Mixter4c5daa42010-08-26 18:35:06 -0700276 FRIEND_TEST(FrequencyCounterTest, GetCycleNumberForWeek);
277 FRIEND_TEST(FrequencyCounterTest, GetCycleNumberForDay);
Ken Mixterccd84c02010-08-16 19:57:13 -0700278
279 void UpdateInternal(int32 count, time_t now);
280 int32 GetCycleNumber(time_t now);
281
282 time_t cycle_duration_;
283 scoped_ptr<TaggedCounterInterface> tagged_counter_;
284};
285
Darin Petkovf1e85e42010-06-10 15:59:53 -0700286} // namespace chromeos_metrics
287
288#endif // METRICS_COUNTER_H_