blob: a1b0ee2309f2d6f28f8c21931b17d8eb960a77c2 [file] [log] [blame]
Yao Chenb3561512017-11-21 18:07:17 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#pragma once
17
18#include "config/ConfigKey.h"
Chenjie Yub038b702017-12-18 15:15:34 -080019#include "statslog.h"
Yao Chenb3561512017-11-21 18:07:17 -080020
Yao Chen69f1baf2017-11-27 17:25:36 -080021#include <gtest/gtest_prod.h>
David Chend9269e22017-12-05 13:43:51 -080022#include <log/log_time.h>
Yao Chenf6723df2018-01-08 15:11:58 -080023#include <list>
Yao Chenb3561512017-11-21 18:07:17 -080024#include <mutex>
25#include <string>
26#include <vector>
27
28namespace android {
29namespace os {
30namespace statsd {
31
Yao Chen20e9e622018-02-28 11:18:51 -080032struct ConfigStats {
33 int32_t uid;
34 int64_t id;
35 int32_t creation_time_sec;
36 int32_t deletion_time_sec = 0;
37 int32_t metric_count;
38 int32_t condition_count;
39 int32_t matcher_count;
40 int32_t alert_count;
41 bool is_valid;
42
43 std::list<int32_t> broadcast_sent_time_sec;
44 std::list<int32_t> data_drop_time_sec;
45 std::list<int32_t> dump_report_time_sec;
46
47 // Stores how many times a matcher have been matched. The map size is capped by kMaxConfigCount.
48 std::map<const int64_t, int> matcher_stats;
49
50 // Stores the number of output tuple of condition trackers when it's bigger than
51 // kDimensionKeySizeSoftLimit. When you see the number is kDimensionKeySizeHardLimit +1,
52 // it means some data has been dropped. The map size is capped by kMaxConfigCount.
53 std::map<const int64_t, int> condition_stats;
54
55 // Stores the number of output tuple of metric producers when it's bigger than
56 // kDimensionKeySizeSoftLimit. When you see the number is kDimensionKeySizeHardLimit +1,
57 // it means some data has been dropped. The map size is capped by kMaxConfigCount.
58 std::map<const int64_t, int> metric_stats;
59
Yangster-mac306ccc22018-03-24 15:03:40 -070060 // Stores the max number of output tuple of dimensions in condition across dimensions in what
61 // when it's bigger than kDimensionKeySizeSoftLimit. When you see the number is
62 // kDimensionKeySizeHardLimit +1, it means some data has been dropped. The map size is capped by
63 // kMaxConfigCount.
64 std::map<const int64_t, int> metric_dimension_in_condition_stats;
65
Yao Chen20e9e622018-02-28 11:18:51 -080066 // Stores the number of times an anomaly detection alert has been declared.
67 // The map size is capped by kMaxConfigCount.
68 std::map<const int64_t, int> alert_stats;
David Chenfaa1af52018-03-30 15:14:04 -070069
70 // Stores the config ID for each sub-config used.
71 std::list<std::pair<const int64_t, const int32_t>> annotations;
Yao Chen20e9e622018-02-28 11:18:51 -080072};
73
74struct UidMapStats {
75 int32_t snapshots;
76 int32_t changes;
77 int32_t bytes_used;
78 int32_t dropped_snapshots;
79 int32_t dropped_changes;
80};
81
Yao Chenb3561512017-11-21 18:07:17 -080082// Keeps track of stats of statsd.
Yao Chen20e9e622018-02-28 11:18:51 -080083// Single instance shared across the process. All public methods are thread safe.
Yao Chenb3561512017-11-21 18:07:17 -080084class StatsdStats {
85public:
86 static StatsdStats& getInstance();
87 ~StatsdStats(){};
88
89 // TODO: set different limit if the device is low ram.
Yao Chen52b478b2018-03-27 10:59:45 -070090 const static int kDimensionKeySizeSoftLimit = 500;
91 const static int kDimensionKeySizeHardLimit = 800;
Yao Chenb3561512017-11-21 18:07:17 -080092
Chenjie Yuc5875052018-03-09 10:13:11 -080093 // Per atom dimension key size limit
94 static const std::map<int, std::pair<size_t, size_t>> kAtomDimensionKeySizeLimitMap;
95
Yao Chen52b478b2018-03-27 10:59:45 -070096 const static int kMaxConfigCountPerUid = 10;
Bookatz1476ef22018-02-13 12:26:01 -080097 const static int kMaxAlertCountPerConfig = 100;
Yao Chen52b478b2018-03-27 10:59:45 -070098 const static int kMaxConditionCountPerConfig = 300;
99 const static int kMaxMetricCountPerConfig = 1000;
100 const static int kMaxMatcherCountPerConfig = 800;
Yao Chenb3561512017-11-21 18:07:17 -0800101
Yao Chenf6723df2018-01-08 15:11:58 -0800102 // The max number of old config stats we keep.
103 const static int kMaxIceBoxSize = 20;
104
Yao Chen884c8c12018-01-26 10:36:25 -0800105 const static int kMaxLoggerErrors = 10;
106
Yao Chen0fac5b12017-11-28 16:07:02 -0800107 const static int kMaxTimestampCount = 20;
108
Yao Chend10f7b12017-12-18 12:53:50 -0800109 const static int kMaxLogSourceCount = 50;
110
David Chen4c6d97a2018-03-22 16:31:40 -0700111 // Max memory allowed for storing metrics per configuration. If this limit is exceeded, statsd
112 // drops the metrics data in memory.
113 static const size_t kMaxMetricsBytesPerConfig = 256 * 1024;
114
115 // Soft memory limit per configuration. Once this limit is exceeded, we begin notifying the
116 // data subscriber that it's time to call getData.
117 static const size_t kBytesPerConfigTriggerGetData = 128 * 1024;
David Chend9269e22017-12-05 13:43:51 -0800118
David Chenc136f452017-11-27 11:52:26 -0800119 // Cap the UID map's memory usage to this. This should be fairly high since the UID information
120 // is critical for understanding the metrics.
121 const static size_t kMaxBytesUsedUidMap = 50 * 1024;
122
David Chend9269e22017-12-05 13:43:51 -0800123 /* Minimum period between two broadcasts in nanoseconds. */
124 static const unsigned long long kMinBroadcastPeriodNs = 60 * NS_PER_SEC;
125
126 /* Min period between two checks of byte size per config key in nanoseconds. */
127 static const unsigned long long kMinByteSizeCheckPeriodNs = 10 * NS_PER_SEC;
128
yro98a28502018-01-18 17:00:14 -0800129 // Maximum age (30 days) that files on disk can exist in seconds.
130 static const int kMaxAgeSecond = 60 * 60 * 24 * 30;
131
132 // Maximum number of files (1000) that can be in stats directory on disk.
133 static const int kMaxFileNumber = 1000;
134
135 // Maximum size of all files that can be written to stats directory on disk.
136 static const int kMaxFileSize = 50 * 1024 * 1024;
137
Chenjie Yufa22d652018-02-05 14:37:48 -0800138 // How long to try to clear puller cache from last time
139 static const long kPullerCacheClearIntervalSec = 1;
140
Yao Chenb3561512017-11-21 18:07:17 -0800141 /**
142 * Report a new config has been received and report the static stats about the config.
143 *
144 * The static stats include: the count of metrics, conditions, matchers, and alerts.
145 * If the config is not valid, this config stats will be put into icebox immediately.
146 */
147 void noteConfigReceived(const ConfigKey& key, int metricsCount, int conditionsCount,
David Chenfaa1af52018-03-30 15:14:04 -0700148 int matchersCount, int alertCount,
149 const std::list<std::pair<const int64_t, const int32_t>>& annotations,
150 bool isValid);
Yao Chenb3561512017-11-21 18:07:17 -0800151 /**
152 * Report a config has been removed.
153 */
154 void noteConfigRemoved(const ConfigKey& key);
155
156 /**
157 * Report a broadcast has been sent to a config owner to collect the data.
158 */
159 void noteBroadcastSent(const ConfigKey& key);
160
161 /**
162 * Report a config's metrics data has been dropped.
163 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800164 void noteDataDropped(const ConfigKey& key);
165
166 /**
167 * Report metrics data report has been sent.
168 *
169 * The report may be requested via StatsManager API, or through adb cmd.
170 */
171 void noteMetricsReportSent(const ConfigKey& key);
Yao Chenb3561512017-11-21 18:07:17 -0800172
173 /**
174 * Report the size of output tuple of a condition.
175 *
176 * Note: only report when the condition has an output dimension, and the tuple
177 * count > kDimensionKeySizeSoftLimit.
178 *
179 * [key]: The config key that this condition belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800180 * [id]: The id of the condition.
Yao Chenb3561512017-11-21 18:07:17 -0800181 * [size]: The output tuple size.
182 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800183 void noteConditionDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800184
185 /**
186 * Report the size of output tuple of a metric.
187 *
188 * Note: only report when the metric has an output dimension, and the tuple
189 * count > kDimensionKeySizeSoftLimit.
190 *
191 * [key]: The config key that this metric belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800192 * [id]: The id of the metric.
Yao Chenb3561512017-11-21 18:07:17 -0800193 * [size]: The output tuple size.
194 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800195 void noteMetricDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800196
Yangster-mac306ccc22018-03-24 15:03:40 -0700197
198 /**
199 * Report the max size of output tuple of dimension in condition across dimensions in what.
200 *
201 * Note: only report when the metric has an output dimension in condition, and the max tuple
202 * count > kDimensionKeySizeSoftLimit.
203 *
204 * [key]: The config key that this metric belongs to.
205 * [id]: The id of the metric.
206 * [size]: The output tuple size.
207 */
208 void noteMetricDimensionInConditionSize(const ConfigKey& key, const int64_t& id, int size);
209
Yao Chenb3561512017-11-21 18:07:17 -0800210 /**
211 * Report a matcher has been matched.
212 *
213 * [key]: The config key that this matcher belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800214 * [id]: The id of the matcher.
Yao Chenb3561512017-11-21 18:07:17 -0800215 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800216 void noteMatcherMatched(const ConfigKey& key, const int64_t& id);
Yao Chenb3561512017-11-21 18:07:17 -0800217
218 /**
Bookatz8f2f3d82017-12-07 13:53:21 -0800219 * Report that an anomaly detection alert has been declared.
220 *
221 * [key]: The config key that this alert belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800222 * [id]: The id of the alert.
Bookatz8f2f3d82017-12-07 13:53:21 -0800223 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800224 void noteAnomalyDeclared(const ConfigKey& key, const int64_t& id);
Bookatz8f2f3d82017-12-07 13:53:21 -0800225
226 /**
Yao Chenb3561512017-11-21 18:07:17 -0800227 * Report an atom event has been logged.
228 */
229 void noteAtomLogged(int atomId, int32_t timeSec);
230
231 /**
Bookatz1d0136d2017-12-01 11:13:32 -0800232 * Report that statsd modified the anomaly alarm registered with StatsCompanionService.
233 */
234 void noteRegisteredAnomalyAlarmChanged();
235
236 /**
Yangster-mac932ecec2018-02-01 10:23:52 -0800237 * Report that statsd modified the periodic alarm registered with StatsCompanionService.
238 */
239 void noteRegisteredPeriodicAlarmChanged();
240
241 /**
David Chenc136f452017-11-27 11:52:26 -0800242 * Records the number of snapshot and delta entries that are being dropped from the uid map.
243 */
244 void noteUidMapDropped(int snapshots, int deltas);
245
246 /**
247 * Updates the number of snapshots currently stored in the uid map.
248 */
249 void setUidMapSnapshots(int snapshots);
250 void setUidMapChanges(int changes);
251 void setCurrentUidMapMemory(int bytes);
252
Chenjie Yub038b702017-12-18 15:15:34 -0800253 // Update minimum interval between pulls for an pulled atom
254 void updateMinPullIntervalSec(int pullAtomId, long intervalSec);
255
256 // Notify pull request for an atom
257 void notePull(int pullAtomId);
258
259 // Notify pull request for an atom served from cached data
260 void notePullFromCache(int pullAtomId);
261
David Chenc136f452017-11-27 11:52:26 -0800262 /**
Yao Chen884c8c12018-01-26 10:36:25 -0800263 * Records statsd met an error while reading from logd.
264 */
265 void noteLoggerError(int error);
266
267 /**
Yao Chenb3561512017-11-21 18:07:17 -0800268 * Reset the historical stats. Including all stats in icebox, and the tracked stats about
269 * metrics, matchers, and atoms. The active configs will be kept and StatsdStats will continue
270 * to collect stats after reset() has been called.
271 */
272 void reset();
273
274 /**
275 * Output the stats in protobuf binary format to [buffer].
276 *
277 * [reset]: whether to clear the historical stats after the call.
278 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800279 void dumpStats(std::vector<uint8_t>* buffer, bool reset);
Yao Chenb3561512017-11-21 18:07:17 -0800280
Yao Chenf5acabe2018-01-17 14:10:34 -0800281 /**
282 * Output statsd stats in human readable format to [out] file.
283 */
284 void dumpStats(FILE* out) const;
285
Chenjie Yub038b702017-12-18 15:15:34 -0800286 typedef struct {
287 long totalPull;
288 long totalPullFromCache;
289 long minPullIntervalSec;
290 } PulledAtomStats;
291
Yao Chenb3561512017-11-21 18:07:17 -0800292private:
293 StatsdStats();
294
295 mutable std::mutex mLock;
296
Yao Chen69f1baf2017-11-27 17:25:36 -0800297 int32_t mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800298
David Chenc136f452017-11-27 11:52:26 -0800299 // Track the number of dropped entries used by the uid map.
Yao Chen20e9e622018-02-28 11:18:51 -0800300 UidMapStats mUidMapStats;
David Chenc136f452017-11-27 11:52:26 -0800301
Yao Chenb3561512017-11-21 18:07:17 -0800302 // The stats about the configs that are still in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800303 // The map size is capped by kMaxConfigCount.
Yao Chen20e9e622018-02-28 11:18:51 -0800304 std::map<const ConfigKey, std::shared_ptr<ConfigStats>> mConfigStats;
Yao Chenb3561512017-11-21 18:07:17 -0800305
306 // Stores the stats for the configs that are no longer in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800307 // The size of the vector is capped by kMaxIceBoxSize.
Yao Chen20e9e622018-02-28 11:18:51 -0800308 std::list<const std::shared_ptr<ConfigStats>> mIceBox;
Yao Chenb3561512017-11-21 18:07:17 -0800309
310 // Stores the number of times a pushed atom is logged.
311 // The size of the vector is the largest pushed atom id in atoms.proto + 1. Atoms
312 // out of that range will be dropped (it's either pulled atoms or test atoms).
313 // This is a vector, not a map because it will be accessed A LOT -- for each stats log.
314 std::vector<int> mPushedAtomStats;
315
Yao Chenf6723df2018-01-08 15:11:58 -0800316 // Maps PullAtomId to its stats. The size is capped by the puller atom counts.
Chenjie Yub038b702017-12-18 15:15:34 -0800317 std::map<int, PulledAtomStats> mPulledAtomStats;
318
Yao Chen884c8c12018-01-26 10:36:25 -0800319 // Logd errors. Size capped by kMaxLoggerErrors.
320 std::list<const std::pair<int, int>> mLoggerErrors;
321
Bookatz1d0136d2017-12-01 11:13:32 -0800322 // Stores the number of times statsd modified the anomaly alarm registered with
323 // StatsCompanionService.
324 int mAnomalyAlarmRegisteredStats = 0;
325
Yangster-mac932ecec2018-02-01 10:23:52 -0800326 // Stores the number of times statsd registers the periodic alarm changes
327 int mPeriodicAlarmRegisteredStats = 0;
328
Yao Chenb3561512017-11-21 18:07:17 -0800329
330 void noteConfigRemovedInternalLocked(const ConfigKey& key);
331
332 void resetInternalLocked();
333
Yao Chen0fac5b12017-11-28 16:07:02 -0800334 void noteDataDropped(const ConfigKey& key, int32_t timeSec);
335
336 void noteMetricsReportSent(const ConfigKey& key, int32_t timeSec);
337
338 void noteBroadcastSent(const ConfigKey& key, int32_t timeSec);
339
Yao Chen20e9e622018-02-28 11:18:51 -0800340 void addToIceBoxLocked(std::shared_ptr<ConfigStats>& stats);
Yao Chenf6723df2018-01-08 15:11:58 -0800341
Yao Chen69f1baf2017-11-27 17:25:36 -0800342 FRIEND_TEST(StatsdStatsTest, TestValidConfigAdd);
343 FRIEND_TEST(StatsdStatsTest, TestInvalidConfigAdd);
344 FRIEND_TEST(StatsdStatsTest, TestConfigRemove);
345 FRIEND_TEST(StatsdStatsTest, TestSubStats);
346 FRIEND_TEST(StatsdStatsTest, TestAtomLog);
Yao Chen0fac5b12017-11-28 16:07:02 -0800347 FRIEND_TEST(StatsdStatsTest, TestTimestampThreshold);
Bookatz1d0136d2017-12-01 11:13:32 -0800348 FRIEND_TEST(StatsdStatsTest, TestAnomalyMonitor);
Yao Chenb3561512017-11-21 18:07:17 -0800349};
350
351} // namespace statsd
352} // namespace os
Stefan Lafonc6f2fa22018-01-04 22:03:29 -0800353} // namespace android