blob: 00bef7560e3862589655c8bf5db3a0bade829d91 [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;
Yangster-macb142cc82018-03-30 15:22:08 -070037 int32_t reset_time_sec = 0;
Yao Chen20e9e622018-02-28 11:18:51 -080038 int32_t metric_count;
39 int32_t condition_count;
40 int32_t matcher_count;
41 int32_t alert_count;
42 bool is_valid;
43
44 std::list<int32_t> broadcast_sent_time_sec;
45 std::list<int32_t> data_drop_time_sec;
46 std::list<int32_t> dump_report_time_sec;
47
48 // Stores how many times a matcher have been matched. The map size is capped by kMaxConfigCount.
49 std::map<const int64_t, int> matcher_stats;
50
51 // Stores the number of output tuple of condition trackers when it's bigger than
52 // kDimensionKeySizeSoftLimit. When you see the number is kDimensionKeySizeHardLimit +1,
53 // it means some data has been dropped. The map size is capped by kMaxConfigCount.
54 std::map<const int64_t, int> condition_stats;
55
56 // Stores the number of output tuple of metric producers when it's bigger than
57 // kDimensionKeySizeSoftLimit. When you see the number is kDimensionKeySizeHardLimit +1,
58 // it means some data has been dropped. The map size is capped by kMaxConfigCount.
59 std::map<const int64_t, int> metric_stats;
60
Yangster-mac306ccc22018-03-24 15:03:40 -070061 // Stores the max number of output tuple of dimensions in condition across dimensions in what
62 // when it's bigger than kDimensionKeySizeSoftLimit. When you see the number is
63 // kDimensionKeySizeHardLimit +1, it means some data has been dropped. The map size is capped by
64 // kMaxConfigCount.
65 std::map<const int64_t, int> metric_dimension_in_condition_stats;
66
Yao Chen20e9e622018-02-28 11:18:51 -080067 // Stores the number of times an anomaly detection alert has been declared.
68 // The map size is capped by kMaxConfigCount.
69 std::map<const int64_t, int> alert_stats;
David Chenfaa1af52018-03-30 15:14:04 -070070
71 // Stores the config ID for each sub-config used.
72 std::list<std::pair<const int64_t, const int32_t>> annotations;
Yao Chen20e9e622018-02-28 11:18:51 -080073};
74
75struct UidMapStats {
76 int32_t snapshots;
77 int32_t changes;
78 int32_t bytes_used;
79 int32_t dropped_snapshots;
80 int32_t dropped_changes;
81};
82
Yao Chenb3561512017-11-21 18:07:17 -080083// Keeps track of stats of statsd.
Yao Chen20e9e622018-02-28 11:18:51 -080084// Single instance shared across the process. All public methods are thread safe.
Yao Chenb3561512017-11-21 18:07:17 -080085class StatsdStats {
86public:
87 static StatsdStats& getInstance();
88 ~StatsdStats(){};
89
90 // TODO: set different limit if the device is low ram.
Yao Chen52b478b2018-03-27 10:59:45 -070091 const static int kDimensionKeySizeSoftLimit = 500;
92 const static int kDimensionKeySizeHardLimit = 800;
Yao Chenb3561512017-11-21 18:07:17 -080093
Chenjie Yuc5875052018-03-09 10:13:11 -080094 // Per atom dimension key size limit
95 static const std::map<int, std::pair<size_t, size_t>> kAtomDimensionKeySizeLimitMap;
96
Yao Chen52b478b2018-03-27 10:59:45 -070097 const static int kMaxConfigCountPerUid = 10;
Bookatz1476ef22018-02-13 12:26:01 -080098 const static int kMaxAlertCountPerConfig = 100;
Yao Chen52b478b2018-03-27 10:59:45 -070099 const static int kMaxConditionCountPerConfig = 300;
100 const static int kMaxMetricCountPerConfig = 1000;
101 const static int kMaxMatcherCountPerConfig = 800;
Yao Chenb3561512017-11-21 18:07:17 -0800102
Yao Chenf6723df2018-01-08 15:11:58 -0800103 // The max number of old config stats we keep.
104 const static int kMaxIceBoxSize = 20;
105
Yao Chen884c8c12018-01-26 10:36:25 -0800106 const static int kMaxLoggerErrors = 10;
107
Yao Chen0fac5b12017-11-28 16:07:02 -0800108 const static int kMaxTimestampCount = 20;
109
Yao Chend10f7b12017-12-18 12:53:50 -0800110 const static int kMaxLogSourceCount = 50;
111
David Chen4c6d97a2018-03-22 16:31:40 -0700112 // Max memory allowed for storing metrics per configuration. If this limit is exceeded, statsd
113 // drops the metrics data in memory.
114 static const size_t kMaxMetricsBytesPerConfig = 256 * 1024;
115
116 // Soft memory limit per configuration. Once this limit is exceeded, we begin notifying the
117 // data subscriber that it's time to call getData.
118 static const size_t kBytesPerConfigTriggerGetData = 128 * 1024;
David Chend9269e22017-12-05 13:43:51 -0800119
David Chenc136f452017-11-27 11:52:26 -0800120 // Cap the UID map's memory usage to this. This should be fairly high since the UID information
121 // is critical for understanding the metrics.
122 const static size_t kMaxBytesUsedUidMap = 50 * 1024;
123
David Chend9269e22017-12-05 13:43:51 -0800124 /* Minimum period between two broadcasts in nanoseconds. */
Yangster-macb142cc82018-03-30 15:22:08 -0700125 static const int64_t kMinBroadcastPeriodNs = 60 * NS_PER_SEC;
David Chend9269e22017-12-05 13:43:51 -0800126
127 /* Min period between two checks of byte size per config key in nanoseconds. */
Yangster-macb142cc82018-03-30 15:22:08 -0700128 static const int64_t kMinByteSizeCheckPeriodNs = 10 * NS_PER_SEC;
David Chend9269e22017-12-05 13:43:51 -0800129
yro98a28502018-01-18 17:00:14 -0800130 // Maximum age (30 days) that files on disk can exist in seconds.
131 static const int kMaxAgeSecond = 60 * 60 * 24 * 30;
132
133 // Maximum number of files (1000) that can be in stats directory on disk.
134 static const int kMaxFileNumber = 1000;
135
136 // Maximum size of all files that can be written to stats directory on disk.
137 static const int kMaxFileSize = 50 * 1024 * 1024;
138
Chenjie Yufa22d652018-02-05 14:37:48 -0800139 // How long to try to clear puller cache from last time
140 static const long kPullerCacheClearIntervalSec = 1;
141
Yao Chenb3561512017-11-21 18:07:17 -0800142 /**
143 * Report a new config has been received and report the static stats about the config.
144 *
145 * The static stats include: the count of metrics, conditions, matchers, and alerts.
146 * If the config is not valid, this config stats will be put into icebox immediately.
147 */
148 void noteConfigReceived(const ConfigKey& key, int metricsCount, int conditionsCount,
David Chenfaa1af52018-03-30 15:14:04 -0700149 int matchersCount, int alertCount,
150 const std::list<std::pair<const int64_t, const int32_t>>& annotations,
151 bool isValid);
Yao Chenb3561512017-11-21 18:07:17 -0800152 /**
153 * Report a config has been removed.
154 */
155 void noteConfigRemoved(const ConfigKey& key);
Yangster-macb142cc82018-03-30 15:22:08 -0700156 /**
157 * Report a config has been reset when ttl expires.
158 */
159 void noteConfigReset(const ConfigKey& key);
Yao Chenb3561512017-11-21 18:07:17 -0800160
161 /**
162 * Report a broadcast has been sent to a config owner to collect the data.
163 */
164 void noteBroadcastSent(const ConfigKey& key);
165
166 /**
167 * Report a config's metrics data has been dropped.
168 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800169 void noteDataDropped(const ConfigKey& key);
170
171 /**
172 * Report metrics data report has been sent.
173 *
174 * The report may be requested via StatsManager API, or through adb cmd.
175 */
176 void noteMetricsReportSent(const ConfigKey& key);
Yao Chenb3561512017-11-21 18:07:17 -0800177
178 /**
179 * Report the size of output tuple of a condition.
180 *
181 * Note: only report when the condition has an output dimension, and the tuple
182 * count > kDimensionKeySizeSoftLimit.
183 *
184 * [key]: The config key that this condition belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800185 * [id]: The id of the condition.
Yao Chenb3561512017-11-21 18:07:17 -0800186 * [size]: The output tuple size.
187 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800188 void noteConditionDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800189
190 /**
191 * Report the size of output tuple of a metric.
192 *
193 * Note: only report when the metric has an output dimension, and the tuple
194 * count > kDimensionKeySizeSoftLimit.
195 *
196 * [key]: The config key that this metric belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800197 * [id]: The id of the metric.
Yao Chenb3561512017-11-21 18:07:17 -0800198 * [size]: The output tuple size.
199 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800200 void noteMetricDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800201
Yangster-mac306ccc22018-03-24 15:03:40 -0700202
203 /**
204 * Report the max size of output tuple of dimension in condition across dimensions in what.
205 *
206 * Note: only report when the metric has an output dimension in condition, and the max tuple
207 * count > kDimensionKeySizeSoftLimit.
208 *
209 * [key]: The config key that this metric belongs to.
210 * [id]: The id of the metric.
211 * [size]: The output tuple size.
212 */
213 void noteMetricDimensionInConditionSize(const ConfigKey& key, const int64_t& id, int size);
214
Yao Chenb3561512017-11-21 18:07:17 -0800215 /**
216 * Report a matcher has been matched.
217 *
218 * [key]: The config key that this matcher belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800219 * [id]: The id of the matcher.
Yao Chenb3561512017-11-21 18:07:17 -0800220 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800221 void noteMatcherMatched(const ConfigKey& key, const int64_t& id);
Yao Chenb3561512017-11-21 18:07:17 -0800222
223 /**
Bookatz8f2f3d82017-12-07 13:53:21 -0800224 * Report that an anomaly detection alert has been declared.
225 *
226 * [key]: The config key that this alert belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800227 * [id]: The id of the alert.
Bookatz8f2f3d82017-12-07 13:53:21 -0800228 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800229 void noteAnomalyDeclared(const ConfigKey& key, const int64_t& id);
Bookatz8f2f3d82017-12-07 13:53:21 -0800230
231 /**
Yao Chenb3561512017-11-21 18:07:17 -0800232 * Report an atom event has been logged.
233 */
234 void noteAtomLogged(int atomId, int32_t timeSec);
235
236 /**
Bookatz1d0136d2017-12-01 11:13:32 -0800237 * Report that statsd modified the anomaly alarm registered with StatsCompanionService.
238 */
239 void noteRegisteredAnomalyAlarmChanged();
240
241 /**
Yangster-mac932ecec2018-02-01 10:23:52 -0800242 * Report that statsd modified the periodic alarm registered with StatsCompanionService.
243 */
244 void noteRegisteredPeriodicAlarmChanged();
245
246 /**
David Chenc136f452017-11-27 11:52:26 -0800247 * Records the number of snapshot and delta entries that are being dropped from the uid map.
248 */
249 void noteUidMapDropped(int snapshots, int deltas);
250
251 /**
252 * Updates the number of snapshots currently stored in the uid map.
253 */
254 void setUidMapSnapshots(int snapshots);
255 void setUidMapChanges(int changes);
256 void setCurrentUidMapMemory(int bytes);
257
Chenjie Yub038b702017-12-18 15:15:34 -0800258 // Update minimum interval between pulls for an pulled atom
259 void updateMinPullIntervalSec(int pullAtomId, long intervalSec);
260
261 // Notify pull request for an atom
262 void notePull(int pullAtomId);
263
264 // Notify pull request for an atom served from cached data
265 void notePullFromCache(int pullAtomId);
266
David Chenc136f452017-11-27 11:52:26 -0800267 /**
Yao Chen884c8c12018-01-26 10:36:25 -0800268 * Records statsd met an error while reading from logd.
269 */
270 void noteLoggerError(int error);
271
272 /**
Yao Chenb3561512017-11-21 18:07:17 -0800273 * Reset the historical stats. Including all stats in icebox, and the tracked stats about
274 * metrics, matchers, and atoms. The active configs will be kept and StatsdStats will continue
275 * to collect stats after reset() has been called.
276 */
277 void reset();
278
279 /**
280 * Output the stats in protobuf binary format to [buffer].
281 *
282 * [reset]: whether to clear the historical stats after the call.
283 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800284 void dumpStats(std::vector<uint8_t>* buffer, bool reset);
Yao Chenb3561512017-11-21 18:07:17 -0800285
Yao Chenf5acabe2018-01-17 14:10:34 -0800286 /**
287 * Output statsd stats in human readable format to [out] file.
288 */
289 void dumpStats(FILE* out) const;
290
Chenjie Yub038b702017-12-18 15:15:34 -0800291 typedef struct {
292 long totalPull;
293 long totalPullFromCache;
294 long minPullIntervalSec;
295 } PulledAtomStats;
296
Yao Chenb3561512017-11-21 18:07:17 -0800297private:
298 StatsdStats();
299
300 mutable std::mutex mLock;
301
Yao Chen69f1baf2017-11-27 17:25:36 -0800302 int32_t mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800303
David Chenc136f452017-11-27 11:52:26 -0800304 // Track the number of dropped entries used by the uid map.
Yao Chen20e9e622018-02-28 11:18:51 -0800305 UidMapStats mUidMapStats;
David Chenc136f452017-11-27 11:52:26 -0800306
Yao Chenb3561512017-11-21 18:07:17 -0800307 // The stats about the configs that are still in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800308 // The map size is capped by kMaxConfigCount.
Yao Chen20e9e622018-02-28 11:18:51 -0800309 std::map<const ConfigKey, std::shared_ptr<ConfigStats>> mConfigStats;
Yao Chenb3561512017-11-21 18:07:17 -0800310
311 // Stores the stats for the configs that are no longer in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800312 // The size of the vector is capped by kMaxIceBoxSize.
Yao Chen20e9e622018-02-28 11:18:51 -0800313 std::list<const std::shared_ptr<ConfigStats>> mIceBox;
Yao Chenb3561512017-11-21 18:07:17 -0800314
315 // Stores the number of times a pushed atom is logged.
316 // The size of the vector is the largest pushed atom id in atoms.proto + 1. Atoms
317 // out of that range will be dropped (it's either pulled atoms or test atoms).
318 // This is a vector, not a map because it will be accessed A LOT -- for each stats log.
319 std::vector<int> mPushedAtomStats;
320
Yao Chenf6723df2018-01-08 15:11:58 -0800321 // Maps PullAtomId to its stats. The size is capped by the puller atom counts.
Chenjie Yub038b702017-12-18 15:15:34 -0800322 std::map<int, PulledAtomStats> mPulledAtomStats;
323
Yao Chen884c8c12018-01-26 10:36:25 -0800324 // Logd errors. Size capped by kMaxLoggerErrors.
325 std::list<const std::pair<int, int>> mLoggerErrors;
326
Bookatz1d0136d2017-12-01 11:13:32 -0800327 // Stores the number of times statsd modified the anomaly alarm registered with
328 // StatsCompanionService.
329 int mAnomalyAlarmRegisteredStats = 0;
330
Yangster-mac932ecec2018-02-01 10:23:52 -0800331 // Stores the number of times statsd registers the periodic alarm changes
332 int mPeriodicAlarmRegisteredStats = 0;
333
Yangster-macb142cc82018-03-30 15:22:08 -0700334 void noteConfigResetInternalLocked(const ConfigKey& key);
Yao Chenb3561512017-11-21 18:07:17 -0800335
336 void noteConfigRemovedInternalLocked(const ConfigKey& key);
337
338 void resetInternalLocked();
339
Yao Chen0fac5b12017-11-28 16:07:02 -0800340 void noteDataDropped(const ConfigKey& key, int32_t timeSec);
341
342 void noteMetricsReportSent(const ConfigKey& key, int32_t timeSec);
343
344 void noteBroadcastSent(const ConfigKey& key, int32_t timeSec);
345
Yao Chen20e9e622018-02-28 11:18:51 -0800346 void addToIceBoxLocked(std::shared_ptr<ConfigStats>& stats);
Yao Chenf6723df2018-01-08 15:11:58 -0800347
Yao Chen69f1baf2017-11-27 17:25:36 -0800348 FRIEND_TEST(StatsdStatsTest, TestValidConfigAdd);
349 FRIEND_TEST(StatsdStatsTest, TestInvalidConfigAdd);
350 FRIEND_TEST(StatsdStatsTest, TestConfigRemove);
351 FRIEND_TEST(StatsdStatsTest, TestSubStats);
352 FRIEND_TEST(StatsdStatsTest, TestAtomLog);
Yao Chen0fac5b12017-11-28 16:07:02 -0800353 FRIEND_TEST(StatsdStatsTest, TestTimestampThreshold);
Bookatz1d0136d2017-12-01 11:13:32 -0800354 FRIEND_TEST(StatsdStatsTest, TestAnomalyMonitor);
Yao Chenb3561512017-11-21 18:07:17 -0800355};
356
357} // namespace statsd
358} // namespace os
Stefan Lafonc6f2fa22018-01-04 22:03:29 -0800359} // namespace android