blob: bd395c4c232b7dfbafa833996e9903ac63ceef4b [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;
69};
70
71struct UidMapStats {
72 int32_t snapshots;
73 int32_t changes;
74 int32_t bytes_used;
75 int32_t dropped_snapshots;
76 int32_t dropped_changes;
77};
78
Yao Chenb3561512017-11-21 18:07:17 -080079// Keeps track of stats of statsd.
Yao Chen20e9e622018-02-28 11:18:51 -080080// Single instance shared across the process. All public methods are thread safe.
Yao Chenb3561512017-11-21 18:07:17 -080081class StatsdStats {
82public:
83 static StatsdStats& getInstance();
84 ~StatsdStats(){};
85
86 // TODO: set different limit if the device is low ram.
Yao Chen52b478b2018-03-27 10:59:45 -070087 const static int kDimensionKeySizeSoftLimit = 500;
88 const static int kDimensionKeySizeHardLimit = 800;
Yao Chenb3561512017-11-21 18:07:17 -080089
Chenjie Yuc5875052018-03-09 10:13:11 -080090 // Per atom dimension key size limit
91 static const std::map<int, std::pair<size_t, size_t>> kAtomDimensionKeySizeLimitMap;
92
Yao Chen52b478b2018-03-27 10:59:45 -070093 const static int kMaxConfigCountPerUid = 10;
Bookatz1476ef22018-02-13 12:26:01 -080094 const static int kMaxAlertCountPerConfig = 100;
Yao Chen52b478b2018-03-27 10:59:45 -070095 const static int kMaxConditionCountPerConfig = 300;
96 const static int kMaxMetricCountPerConfig = 1000;
97 const static int kMaxMatcherCountPerConfig = 800;
Yao Chenb3561512017-11-21 18:07:17 -080098
Yao Chenf6723df2018-01-08 15:11:58 -080099 // The max number of old config stats we keep.
100 const static int kMaxIceBoxSize = 20;
101
Yao Chen884c8c12018-01-26 10:36:25 -0800102 const static int kMaxLoggerErrors = 10;
103
Yao Chen0fac5b12017-11-28 16:07:02 -0800104 const static int kMaxTimestampCount = 20;
105
Yao Chend10f7b12017-12-18 12:53:50 -0800106 const static int kMaxLogSourceCount = 50;
107
David Chen4c6d97a2018-03-22 16:31:40 -0700108 // Max memory allowed for storing metrics per configuration. If this limit is exceeded, statsd
109 // drops the metrics data in memory.
110 static const size_t kMaxMetricsBytesPerConfig = 256 * 1024;
111
112 // Soft memory limit per configuration. Once this limit is exceeded, we begin notifying the
113 // data subscriber that it's time to call getData.
114 static const size_t kBytesPerConfigTriggerGetData = 128 * 1024;
David Chend9269e22017-12-05 13:43:51 -0800115
David Chenc136f452017-11-27 11:52:26 -0800116 // Cap the UID map's memory usage to this. This should be fairly high since the UID information
117 // is critical for understanding the metrics.
118 const static size_t kMaxBytesUsedUidMap = 50 * 1024;
119
David Chend9269e22017-12-05 13:43:51 -0800120 /* Minimum period between two broadcasts in nanoseconds. */
121 static const unsigned long long kMinBroadcastPeriodNs = 60 * NS_PER_SEC;
122
123 /* Min period between two checks of byte size per config key in nanoseconds. */
124 static const unsigned long long kMinByteSizeCheckPeriodNs = 10 * NS_PER_SEC;
125
yro98a28502018-01-18 17:00:14 -0800126 // Maximum age (30 days) that files on disk can exist in seconds.
127 static const int kMaxAgeSecond = 60 * 60 * 24 * 30;
128
129 // Maximum number of files (1000) that can be in stats directory on disk.
130 static const int kMaxFileNumber = 1000;
131
132 // Maximum size of all files that can be written to stats directory on disk.
133 static const int kMaxFileSize = 50 * 1024 * 1024;
134
Chenjie Yufa22d652018-02-05 14:37:48 -0800135 // How long to try to clear puller cache from last time
136 static const long kPullerCacheClearIntervalSec = 1;
137
Yao Chenb3561512017-11-21 18:07:17 -0800138 /**
139 * Report a new config has been received and report the static stats about the config.
140 *
141 * The static stats include: the count of metrics, conditions, matchers, and alerts.
142 * If the config is not valid, this config stats will be put into icebox immediately.
143 */
144 void noteConfigReceived(const ConfigKey& key, int metricsCount, int conditionsCount,
145 int matchersCount, int alertCount, bool isValid);
146 /**
147 * Report a config has been removed.
148 */
149 void noteConfigRemoved(const ConfigKey& key);
150
151 /**
152 * Report a broadcast has been sent to a config owner to collect the data.
153 */
154 void noteBroadcastSent(const ConfigKey& key);
155
156 /**
157 * Report a config's metrics data has been dropped.
158 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800159 void noteDataDropped(const ConfigKey& key);
160
161 /**
162 * Report metrics data report has been sent.
163 *
164 * The report may be requested via StatsManager API, or through adb cmd.
165 */
166 void noteMetricsReportSent(const ConfigKey& key);
Yao Chenb3561512017-11-21 18:07:17 -0800167
168 /**
169 * Report the size of output tuple of a condition.
170 *
171 * Note: only report when the condition has an output dimension, and the tuple
172 * count > kDimensionKeySizeSoftLimit.
173 *
174 * [key]: The config key that this condition belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800175 * [id]: The id of the condition.
Yao Chenb3561512017-11-21 18:07:17 -0800176 * [size]: The output tuple size.
177 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800178 void noteConditionDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800179
180 /**
181 * Report the size of output tuple of a metric.
182 *
183 * Note: only report when the metric has an output dimension, and the tuple
184 * count > kDimensionKeySizeSoftLimit.
185 *
186 * [key]: The config key that this metric belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800187 * [id]: The id of the metric.
Yao Chenb3561512017-11-21 18:07:17 -0800188 * [size]: The output tuple size.
189 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800190 void noteMetricDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800191
Yangster-mac306ccc22018-03-24 15:03:40 -0700192
193 /**
194 * Report the max size of output tuple of dimension in condition across dimensions in what.
195 *
196 * Note: only report when the metric has an output dimension in condition, and the max tuple
197 * count > kDimensionKeySizeSoftLimit.
198 *
199 * [key]: The config key that this metric belongs to.
200 * [id]: The id of the metric.
201 * [size]: The output tuple size.
202 */
203 void noteMetricDimensionInConditionSize(const ConfigKey& key, const int64_t& id, int size);
204
Yao Chenb3561512017-11-21 18:07:17 -0800205 /**
206 * Report a matcher has been matched.
207 *
208 * [key]: The config key that this matcher belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800209 * [id]: The id of the matcher.
Yao Chenb3561512017-11-21 18:07:17 -0800210 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800211 void noteMatcherMatched(const ConfigKey& key, const int64_t& id);
Yao Chenb3561512017-11-21 18:07:17 -0800212
213 /**
Bookatz8f2f3d82017-12-07 13:53:21 -0800214 * Report that an anomaly detection alert has been declared.
215 *
216 * [key]: The config key that this alert belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800217 * [id]: The id of the alert.
Bookatz8f2f3d82017-12-07 13:53:21 -0800218 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800219 void noteAnomalyDeclared(const ConfigKey& key, const int64_t& id);
Bookatz8f2f3d82017-12-07 13:53:21 -0800220
221 /**
Yao Chenb3561512017-11-21 18:07:17 -0800222 * Report an atom event has been logged.
223 */
224 void noteAtomLogged(int atomId, int32_t timeSec);
225
226 /**
Bookatz1d0136d2017-12-01 11:13:32 -0800227 * Report that statsd modified the anomaly alarm registered with StatsCompanionService.
228 */
229 void noteRegisteredAnomalyAlarmChanged();
230
231 /**
Yangster-mac932ecec2018-02-01 10:23:52 -0800232 * Report that statsd modified the periodic alarm registered with StatsCompanionService.
233 */
234 void noteRegisteredPeriodicAlarmChanged();
235
236 /**
David Chenc136f452017-11-27 11:52:26 -0800237 * Records the number of snapshot and delta entries that are being dropped from the uid map.
238 */
239 void noteUidMapDropped(int snapshots, int deltas);
240
241 /**
242 * Updates the number of snapshots currently stored in the uid map.
243 */
244 void setUidMapSnapshots(int snapshots);
245 void setUidMapChanges(int changes);
246 void setCurrentUidMapMemory(int bytes);
247
Chenjie Yub038b702017-12-18 15:15:34 -0800248 // Update minimum interval between pulls for an pulled atom
249 void updateMinPullIntervalSec(int pullAtomId, long intervalSec);
250
251 // Notify pull request for an atom
252 void notePull(int pullAtomId);
253
254 // Notify pull request for an atom served from cached data
255 void notePullFromCache(int pullAtomId);
256
David Chenc136f452017-11-27 11:52:26 -0800257 /**
Yao Chen884c8c12018-01-26 10:36:25 -0800258 * Records statsd met an error while reading from logd.
259 */
260 void noteLoggerError(int error);
261
262 /**
Yao Chenb3561512017-11-21 18:07:17 -0800263 * Reset the historical stats. Including all stats in icebox, and the tracked stats about
264 * metrics, matchers, and atoms. The active configs will be kept and StatsdStats will continue
265 * to collect stats after reset() has been called.
266 */
267 void reset();
268
269 /**
270 * Output the stats in protobuf binary format to [buffer].
271 *
272 * [reset]: whether to clear the historical stats after the call.
273 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800274 void dumpStats(std::vector<uint8_t>* buffer, bool reset);
Yao Chenb3561512017-11-21 18:07:17 -0800275
Yao Chenf5acabe2018-01-17 14:10:34 -0800276 /**
277 * Output statsd stats in human readable format to [out] file.
278 */
279 void dumpStats(FILE* out) const;
280
Chenjie Yub038b702017-12-18 15:15:34 -0800281 typedef struct {
282 long totalPull;
283 long totalPullFromCache;
284 long minPullIntervalSec;
285 } PulledAtomStats;
286
Yao Chenb3561512017-11-21 18:07:17 -0800287private:
288 StatsdStats();
289
290 mutable std::mutex mLock;
291
Yao Chen69f1baf2017-11-27 17:25:36 -0800292 int32_t mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800293
David Chenc136f452017-11-27 11:52:26 -0800294 // Track the number of dropped entries used by the uid map.
Yao Chen20e9e622018-02-28 11:18:51 -0800295 UidMapStats mUidMapStats;
David Chenc136f452017-11-27 11:52:26 -0800296
Yao Chenb3561512017-11-21 18:07:17 -0800297 // The stats about the configs that are still in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800298 // The map size is capped by kMaxConfigCount.
Yao Chen20e9e622018-02-28 11:18:51 -0800299 std::map<const ConfigKey, std::shared_ptr<ConfigStats>> mConfigStats;
Yao Chenb3561512017-11-21 18:07:17 -0800300
301 // Stores the stats for the configs that are no longer in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800302 // The size of the vector is capped by kMaxIceBoxSize.
Yao Chen20e9e622018-02-28 11:18:51 -0800303 std::list<const std::shared_ptr<ConfigStats>> mIceBox;
Yao Chenb3561512017-11-21 18:07:17 -0800304
305 // Stores the number of times a pushed atom is logged.
306 // The size of the vector is the largest pushed atom id in atoms.proto + 1. Atoms
307 // out of that range will be dropped (it's either pulled atoms or test atoms).
308 // This is a vector, not a map because it will be accessed A LOT -- for each stats log.
309 std::vector<int> mPushedAtomStats;
310
Yao Chenf6723df2018-01-08 15:11:58 -0800311 // Maps PullAtomId to its stats. The size is capped by the puller atom counts.
Chenjie Yub038b702017-12-18 15:15:34 -0800312 std::map<int, PulledAtomStats> mPulledAtomStats;
313
Yao Chen884c8c12018-01-26 10:36:25 -0800314 // Logd errors. Size capped by kMaxLoggerErrors.
315 std::list<const std::pair<int, int>> mLoggerErrors;
316
Bookatz1d0136d2017-12-01 11:13:32 -0800317 // Stores the number of times statsd modified the anomaly alarm registered with
318 // StatsCompanionService.
319 int mAnomalyAlarmRegisteredStats = 0;
320
Yangster-mac932ecec2018-02-01 10:23:52 -0800321 // Stores the number of times statsd registers the periodic alarm changes
322 int mPeriodicAlarmRegisteredStats = 0;
323
Yao Chenb3561512017-11-21 18:07:17 -0800324
325 void noteConfigRemovedInternalLocked(const ConfigKey& key);
326
327 void resetInternalLocked();
328
Yao Chen0fac5b12017-11-28 16:07:02 -0800329 void noteDataDropped(const ConfigKey& key, int32_t timeSec);
330
331 void noteMetricsReportSent(const ConfigKey& key, int32_t timeSec);
332
333 void noteBroadcastSent(const ConfigKey& key, int32_t timeSec);
334
Yao Chen20e9e622018-02-28 11:18:51 -0800335 void addToIceBoxLocked(std::shared_ptr<ConfigStats>& stats);
Yao Chenf6723df2018-01-08 15:11:58 -0800336
Yao Chen69f1baf2017-11-27 17:25:36 -0800337 FRIEND_TEST(StatsdStatsTest, TestValidConfigAdd);
338 FRIEND_TEST(StatsdStatsTest, TestInvalidConfigAdd);
339 FRIEND_TEST(StatsdStatsTest, TestConfigRemove);
340 FRIEND_TEST(StatsdStatsTest, TestSubStats);
341 FRIEND_TEST(StatsdStatsTest, TestAtomLog);
Yao Chen0fac5b12017-11-28 16:07:02 -0800342 FRIEND_TEST(StatsdStatsTest, TestTimestampThreshold);
Bookatz1d0136d2017-12-01 11:13:32 -0800343 FRIEND_TEST(StatsdStatsTest, TestAnomalyMonitor);
Yao Chenb3561512017-11-21 18:07:17 -0800344};
345
346} // namespace statsd
347} // namespace os
Stefan Lafonc6f2fa22018-01-04 22:03:29 -0800348} // namespace android