1 // Copyright 2012 The Chromium Authors 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 BASE_METRICS_HISTOGRAM_BASE_H_ 6 #define BASE_METRICS_HISTOGRAM_BASE_H_ 7 8 #include <limits.h> 9 #include <stddef.h> 10 #include <stdint.h> 11 12 #include <atomic> 13 #include <memory> 14 #include <string> 15 #include <string_view> 16 17 #include "base/atomicops.h" 18 #include "base/base_export.h" 19 #include "base/time/time.h" 20 #include "base/values.h" 21 22 namespace base { 23 24 class Value; 25 class HistogramBase; 26 class HistogramSamples; 27 class Pickle; 28 class PickleIterator; 29 30 //////////////////////////////////////////////////////////////////////////////// 31 // This enum is used to facilitate deserialization of histograms from other 32 // processes into the browser. If you create another class that inherits from 33 // HistogramBase, add new histogram types and names below. 34 35 enum HistogramType { 36 HISTOGRAM, 37 LINEAR_HISTOGRAM, 38 BOOLEAN_HISTOGRAM, 39 CUSTOM_HISTOGRAM, 40 SPARSE_HISTOGRAM, 41 DUMMY_HISTOGRAM, 42 }; 43 44 // Controls the verbosity of the information when the histogram is serialized to 45 // a JSON. 46 // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.base.metrics 47 enum JSONVerbosityLevel { 48 // The histogram is completely serialized. 49 JSON_VERBOSITY_LEVEL_FULL, 50 // The bucket information is not serialized. 51 JSON_VERBOSITY_LEVEL_OMIT_BUCKETS, 52 }; 53 54 std::string HistogramTypeToString(HistogramType type); 55 56 // This enum is used for reporting how many histograms and of what types and 57 // variations are being created. It has to be in the main .h file so it is 58 // visible to files that define the various histogram types. 59 enum HistogramReport { 60 // Count the number of reports created. The other counts divided by this 61 // number will give the average per run of the program. 62 HISTOGRAM_REPORT_CREATED = 0, 63 64 // Count the total number of histograms created. It is the limit against 65 // which all others are compared. 66 HISTOGRAM_REPORT_HISTOGRAM_CREATED = 1, 67 68 // Count the total number of histograms looked-up. It's better to cache 69 // the result of a single lookup rather than do it repeatedly. 70 HISTOGRAM_REPORT_HISTOGRAM_LOOKUP = 2, 71 72 // These count the individual histogram types. This must follow the order 73 // of HistogramType above. 74 HISTOGRAM_REPORT_TYPE_LOGARITHMIC = 3, 75 HISTOGRAM_REPORT_TYPE_LINEAR = 4, 76 HISTOGRAM_REPORT_TYPE_BOOLEAN = 5, 77 HISTOGRAM_REPORT_TYPE_CUSTOM = 6, 78 HISTOGRAM_REPORT_TYPE_SPARSE = 7, 79 80 // These indicate the individual flags that were set. 81 HISTOGRAM_REPORT_FLAG_UMA_TARGETED = 8, 82 HISTOGRAM_REPORT_FLAG_UMA_STABILITY = 9, 83 HISTOGRAM_REPORT_FLAG_PERSISTENT = 10, 84 85 // This must be last. 86 HISTOGRAM_REPORT_MAX = 11 87 }; 88 89 // Create or find existing histogram that matches the pickled info. 90 // Returns NULL if the pickled data has problems. 91 BASE_EXPORT HistogramBase* DeserializeHistogramInfo(base::PickleIterator* iter); 92 93 //////////////////////////////////////////////////////////////////////////////// 94 95 class BASE_EXPORT HistogramBase { 96 public: 97 typedef int32_t Sample; // Used for samples. 98 typedef subtle::Atomic32 AtomicCount; // Used to count samples. 99 typedef int32_t Count; // Used to manipulate counts in temporaries. 100 101 static const Sample kSampleType_MAX; // INT_MAX 102 103 enum Flags { 104 kNoFlags = 0x0, 105 106 // Histogram should be UMA uploaded. 107 kUmaTargetedHistogramFlag = 0x1, 108 109 // Indicates that this is a stability histogram. This flag exists to specify 110 // which histograms should be included in the initial stability log. Please 111 // refer to |MetricsService::PrepareInitialStabilityLog|. 112 kUmaStabilityHistogramFlag = kUmaTargetedHistogramFlag | 0x2, 113 114 // Indicates that the histogram was pickled to be sent across an IPC 115 // Channel. If we observe this flag on a histogram being aggregated into 116 // after IPC, then we are running in a single process mode, and the 117 // aggregation should not take place (as we would be aggregating back into 118 // the source histogram!). 119 kIPCSerializationSourceFlag = 0x10, 120 121 // Indicates that a callback exists for when a new sample is recorded on 122 // this histogram. We store this as a flag with the histogram since 123 // histograms can be in performance critical code, and this allows us 124 // to shortcut looking up the callback if it doesn't exist. 125 kCallbackExists = 0x20, 126 127 // Indicates that the histogram is held in "persistent" memory and may 128 // be accessible between processes. This is only possible if such a 129 // memory segment has been created/attached, used to create a Persistent- 130 // MemoryAllocator, and that loaded into the Histogram module before this 131 // histogram is created. 132 kIsPersistent = 0x40, 133 }; 134 135 // Histogram data inconsistency types. 136 enum Inconsistency : uint32_t { 137 NO_INCONSISTENCIES = 0x0, 138 RANGE_CHECKSUM_ERROR = 0x1, 139 BUCKET_ORDER_ERROR = 0x2, 140 COUNT_HIGH_ERROR = 0x4, 141 COUNT_LOW_ERROR = 0x8, 142 143 NEVER_EXCEEDED_VALUE = 0x10, 144 }; 145 146 // Construct the base histogram. The name is not copied; it's up to the 147 // caller to ensure that it lives at least as long as this object. 148 explicit HistogramBase(const char* name); 149 150 HistogramBase(const HistogramBase&) = delete; 151 HistogramBase& operator=(const HistogramBase&) = delete; 152 153 virtual ~HistogramBase(); 154 histogram_name()155 const char* histogram_name() const { return histogram_name_; } 156 157 // Compares |name| to the histogram name and triggers a DCHECK if they do not 158 // match. This is a helper function used by histogram macros, which results in 159 // in more compact machine code being generated by the macros. 160 virtual void CheckName(std::string_view name) const; 161 162 // Get a unique ID for this histogram's samples. 163 virtual uint64_t name_hash() const = 0; 164 165 // Operations with Flags enum. flags()166 int32_t flags() const { return flags_.load(std::memory_order_relaxed); } 167 void SetFlags(int32_t flags); 168 void ClearFlags(int32_t flags); 169 bool HasFlags(int32_t flags) const; 170 171 virtual HistogramType GetHistogramType() const = 0; 172 173 // Whether the histogram has construction arguments as parameters specified. 174 // For histograms that don't have the concept of minimum, maximum or 175 // bucket_count, this function always returns false. 176 virtual bool HasConstructionArguments(Sample expected_minimum, 177 Sample expected_maximum, 178 size_t expected_bucket_count) const = 0; 179 180 virtual void Add(Sample value) = 0; 181 182 // In Add function the |value| bucket is increased by one, but in some use 183 // cases we need to increase this value by an arbitrary integer. AddCount 184 // function increases the |value| bucket by |count|. |count| should be greater 185 // than or equal to 1. 186 virtual void AddCount(Sample value, int count) = 0; 187 188 // Similar to above but divides |count| by the |scale| amount. Probabilistic 189 // rounding is used to yield a reasonably accurate total when many samples 190 // are added. Methods for common cases of scales 1000 and 1024 are included. 191 // The ScaledLinearHistogram (which can also used be for enumerations) may be 192 // a better (and faster) solution. 193 void AddScaled(Sample value, int count, int scale); 194 void AddKilo(Sample value, int count); // scale=1000 195 void AddKiB(Sample value, int count); // scale=1024 196 197 // Convenient functions that call Add(Sample). AddTime(const TimeDelta & time)198 void AddTime(const TimeDelta& time) { AddTimeMillisecondsGranularity(time); } 199 void AddTimeMillisecondsGranularity(const TimeDelta& time); 200 // Note: AddTimeMicrosecondsGranularity() drops the report if this client 201 // doesn't have a high-resolution clock. 202 void AddTimeMicrosecondsGranularity(const TimeDelta& time); 203 void AddBoolean(bool value); 204 205 virtual void AddSamples(const HistogramSamples& samples) = 0; 206 virtual bool AddSamplesFromPickle(base::PickleIterator* iter) = 0; 207 208 // Serialize the histogram info into |pickle|. 209 // Note: This only serializes the construction arguments of the histogram, but 210 // does not serialize the samples. 211 void SerializeInfo(base::Pickle* pickle) const; 212 213 // Try to find out data corruption from histogram and the samples. 214 // The returned value is a combination of Inconsistency enum. 215 virtual uint32_t FindCorruption(const HistogramSamples& samples) const; 216 217 // Snapshot the current complete set of sample data. 218 // Note that histogram data is stored per-process. The browser process 219 // periodically ingests data from subprocesses. As such, the browser 220 // process can see histogram data from any process but other processes 221 // can only see histogram data recorded in the subprocess. 222 // Moreover, the data returned here may not be up to date: 223 // - this function does not use a lock so data might not be synced 224 // (e.g., across cpu caches) 225 // - in the browser process, the data from subprocesses may not have 226 // synced data from subprocesses via MergeHistogramDeltas() recently. 227 // 228 // Override with atomic/locked snapshot if needed. 229 // NOTE: this data can overflow for long-running sessions. It should be 230 // handled with care and this method is recommended to be used only 231 // in about:histograms and test code. 232 virtual std::unique_ptr<HistogramSamples> SnapshotSamples() const = 0; 233 234 // Returns a copy of the samples that have not yet been logged. To mark the 235 // returned samples as logged, see MarkSamplesAsLogged(). 236 // 237 // See additional caveats by SnapshotSamples(). 238 // 239 // WARNING: This may be called from a background thread by the metrics 240 // collection system. Do not make a call to this unless it was properly vetted 241 // by someone familiar with the system. 242 // TODO(crbug/1052796): Consider gating this behind a PassKey, so that 243 // eventually, only StatisticsRecorder can use this. 244 virtual std::unique_ptr<HistogramSamples> SnapshotUnloggedSamples() const = 0; 245 246 // Marks the passed |samples| as logged. More formally, the |samples| passed 247 // will not appear in the samples returned by a subsequent call to 248 // SnapshotDelta(). 249 // 250 // See additional caveats by SnapshotSamples(). 251 // 252 // WARNING: This may be called from a background thread by the metrics 253 // collection system. Do not make a call to this unless it was properly vetted 254 // by someone familiar with the system. 255 // TODO(crbug/1052796): Consider gating this behind a PassKey, so that 256 // eventually, only StatisticsRecorder can use this. 257 virtual void MarkSamplesAsLogged(const HistogramSamples& samples) = 0; 258 259 // Calculate the change (delta) in histogram counts since the previous call 260 // to this method. Each successive call will return only those counts changed 261 // since the last call. Calls to MarkSamplesAsLogged() will also affect the 262 // samples returned. Logically, this function is equivalent to a call to 263 // SnapshotUnloggedSamples() followed by a call to MarkSamplesAsLogged(). 264 // 265 // See additional caveats by SnapshotSamples(). 266 // 267 // WARNING: This may be called from a background thread by the metrics 268 // collection system. Do not make a call to this unless it was properly vetted 269 // by someone familiar with the system. 270 virtual std::unique_ptr<HistogramSamples> SnapshotDelta() = 0; 271 272 // Calculate the change (delta) in histogram counts since the previous call 273 // to SnapshotDelta() but do so without modifying any internal data as to 274 // what was previous logged. After such a call, no further calls to this 275 // method or to SnapshotDelta() should be done as the result would include 276 // data previously returned. Because no internal data is changed, this call 277 // can be made on "const" histograms such as those with data held in 278 // read-only memory. 279 // 280 // See additional caveats by SnapshotSamples(). 281 virtual std::unique_ptr<HistogramSamples> SnapshotFinalDelta() const = 0; 282 283 // The following method provides graphical histogram displays. 284 virtual void WriteAscii(std::string* output) const; 285 286 // Returns histograms data as a Dict (or an empty dict if not available), 287 // with the following format: 288 // {"header": "Name of the histogram with samples, mean, and/or flags", 289 // "body": "ASCII histogram representation"} 290 virtual base::Value::Dict ToGraphDict() const = 0; 291 292 // Produce a JSON representation of the histogram with |verbosity_level| as 293 // the serialization verbosity. This is implemented with the help of 294 // GetParameters and GetCountAndBucketData; overwrite them to customize the 295 // output. 296 void WriteJSON(std::string* output, JSONVerbosityLevel verbosity_level) const; 297 298 protected: 299 enum ReportActivity { HISTOGRAM_CREATED, HISTOGRAM_LOOKUP }; 300 301 struct BASE_EXPORT CountAndBucketData { 302 Count count; 303 int64_t sum; 304 Value::List buckets; 305 306 CountAndBucketData(Count count, int64_t sum, Value::List buckets); 307 ~CountAndBucketData(); 308 309 CountAndBucketData(CountAndBucketData&& other); 310 CountAndBucketData& operator=(CountAndBucketData&& other); 311 }; 312 313 // Subclasses should implement this function to make SerializeInfo work. 314 virtual void SerializeInfoImpl(base::Pickle* pickle) const = 0; 315 316 // Writes information about the construction parameters in |params|. 317 virtual Value::Dict GetParameters() const = 0; 318 319 // Returns information about the current (non-empty) buckets and their sample 320 // counts to |buckets|, the total sample count to |count| and the total sum 321 // to |sum|. 322 CountAndBucketData GetCountAndBucketData() const; 323 324 // Produces an actual graph (set of blank vs non blank char's) for a bucket. 325 void WriteAsciiBucketGraph(double x_count, 326 int line_length, 327 std::string* output) const; 328 329 // Return a string description of what goes in a given bucket. 330 const std::string GetSimpleAsciiBucketRange(Sample sample) const; 331 332 // Write textual description of the bucket contents (relative to histogram). 333 // Output is the count in the buckets, as well as the percentage. 334 void WriteAsciiBucketValue(Count current, 335 double scaled_sum, 336 std::string* output) const; 337 338 // Retrieves the registered callbacks for this histogram, if any, and runs 339 // them passing |sample| as the parameter. 340 void FindAndRunCallbacks(Sample sample) const; 341 342 // Gets a permanent string that can be used for histogram objects when the 343 // original is not a code constant or held in persistent memory. 344 static const char* GetPermanentName(std::string_view name); 345 346 private: 347 friend class HistogramBaseTest; 348 349 // A pointer to permanent storage where the histogram name is held. This can 350 // be code space or the output of GetPermanentName() or any other storage 351 // that is known to never change. This is not std::string_view because (a) 352 // char* is 1/2 the size and (b) std::string_view transparently casts from 353 // std::string which can easily lead to a pointer to non-permanent space. For 354 // persistent histograms, this will simply point into the persistent memory 355 // segment, thus avoiding duplication. For heap histograms, the 356 // GetPermanentName method will create the necessary copy. 357 const char* const histogram_name_; 358 359 // Additional information about the histogram. 360 std::atomic<int32_t> flags_{0}; 361 }; 362 363 } // namespace base 364 365 #endif // BASE_METRICS_HISTOGRAM_BASE_H_ 366