blob: a4f64ddfd3a5ee2c01f703a5568ef6bdb61c396f [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
60 // Stores the number of times an anomaly detection alert has been declared.
61 // The map size is capped by kMaxConfigCount.
62 std::map<const int64_t, int> alert_stats;
63};
64
65struct UidMapStats {
66 int32_t snapshots;
67 int32_t changes;
68 int32_t bytes_used;
69 int32_t dropped_snapshots;
70 int32_t dropped_changes;
71};
72
Yao Chenb3561512017-11-21 18:07:17 -080073// Keeps track of stats of statsd.
Yao Chen20e9e622018-02-28 11:18:51 -080074// Single instance shared across the process. All public methods are thread safe.
Yao Chenb3561512017-11-21 18:07:17 -080075class StatsdStats {
76public:
77 static StatsdStats& getInstance();
78 ~StatsdStats(){};
79
80 // TODO: set different limit if the device is low ram.
81 const static int kDimensionKeySizeSoftLimit = 300;
82 const static int kDimensionKeySizeHardLimit = 500;
83
84 const static int kMaxConfigCount = 10;
Bookatz1476ef22018-02-13 12:26:01 -080085 const static int kMaxAlertCountPerConfig = 100;
Yao Chenb3561512017-11-21 18:07:17 -080086 const static int kMaxConditionCountPerConfig = 200;
87 const static int kMaxMetricCountPerConfig = 300;
88 const static int kMaxMatcherCountPerConfig = 500;
89
Yao Chenf6723df2018-01-08 15:11:58 -080090 // The max number of old config stats we keep.
91 const static int kMaxIceBoxSize = 20;
92
Yao Chen884c8c12018-01-26 10:36:25 -080093 const static int kMaxLoggerErrors = 10;
94
Yao Chen0fac5b12017-11-28 16:07:02 -080095 const static int kMaxTimestampCount = 20;
96
Yao Chend10f7b12017-12-18 12:53:50 -080097 const static int kMaxLogSourceCount = 50;
98
David Chen4c6d97a2018-03-22 16:31:40 -070099 // Max memory allowed for storing metrics per configuration. If this limit is exceeded, statsd
100 // drops the metrics data in memory.
101 static const size_t kMaxMetricsBytesPerConfig = 256 * 1024;
102
103 // Soft memory limit per configuration. Once this limit is exceeded, we begin notifying the
104 // data subscriber that it's time to call getData.
105 static const size_t kBytesPerConfigTriggerGetData = 128 * 1024;
David Chend9269e22017-12-05 13:43:51 -0800106
David Chenc136f452017-11-27 11:52:26 -0800107 // Cap the UID map's memory usage to this. This should be fairly high since the UID information
108 // is critical for understanding the metrics.
109 const static size_t kMaxBytesUsedUidMap = 50 * 1024;
110
David Chend9269e22017-12-05 13:43:51 -0800111 /* Minimum period between two broadcasts in nanoseconds. */
112 static const unsigned long long kMinBroadcastPeriodNs = 60 * NS_PER_SEC;
113
114 /* Min period between two checks of byte size per config key in nanoseconds. */
115 static const unsigned long long kMinByteSizeCheckPeriodNs = 10 * NS_PER_SEC;
116
yro98a28502018-01-18 17:00:14 -0800117 // Maximum age (30 days) that files on disk can exist in seconds.
118 static const int kMaxAgeSecond = 60 * 60 * 24 * 30;
119
120 // Maximum number of files (1000) that can be in stats directory on disk.
121 static const int kMaxFileNumber = 1000;
122
123 // Maximum size of all files that can be written to stats directory on disk.
124 static const int kMaxFileSize = 50 * 1024 * 1024;
125
Chenjie Yufa22d652018-02-05 14:37:48 -0800126 // How long to try to clear puller cache from last time
127 static const long kPullerCacheClearIntervalSec = 1;
128
Yao Chenb3561512017-11-21 18:07:17 -0800129 /**
130 * Report a new config has been received and report the static stats about the config.
131 *
132 * The static stats include: the count of metrics, conditions, matchers, and alerts.
133 * If the config is not valid, this config stats will be put into icebox immediately.
134 */
135 void noteConfigReceived(const ConfigKey& key, int metricsCount, int conditionsCount,
136 int matchersCount, int alertCount, bool isValid);
137 /**
138 * Report a config has been removed.
139 */
140 void noteConfigRemoved(const ConfigKey& key);
141
142 /**
143 * Report a broadcast has been sent to a config owner to collect the data.
144 */
145 void noteBroadcastSent(const ConfigKey& key);
146
147 /**
148 * Report a config's metrics data has been dropped.
149 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800150 void noteDataDropped(const ConfigKey& key);
151
152 /**
153 * Report metrics data report has been sent.
154 *
155 * The report may be requested via StatsManager API, or through adb cmd.
156 */
157 void noteMetricsReportSent(const ConfigKey& key);
Yao Chenb3561512017-11-21 18:07:17 -0800158
159 /**
160 * Report the size of output tuple of a condition.
161 *
162 * Note: only report when the condition has an output dimension, and the tuple
163 * count > kDimensionKeySizeSoftLimit.
164 *
165 * [key]: The config key that this condition belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800166 * [id]: The id of the condition.
Yao Chenb3561512017-11-21 18:07:17 -0800167 * [size]: The output tuple size.
168 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800169 void noteConditionDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800170
171 /**
172 * Report the size of output tuple of a metric.
173 *
174 * Note: only report when the metric has an output dimension, and the tuple
175 * count > kDimensionKeySizeSoftLimit.
176 *
177 * [key]: The config key that this metric belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800178 * [id]: The id of the metric.
Yao Chenb3561512017-11-21 18:07:17 -0800179 * [size]: The output tuple size.
180 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800181 void noteMetricDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800182
183 /**
184 * Report a matcher has been matched.
185 *
186 * [key]: The config key that this matcher belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800187 * [id]: The id of the matcher.
Yao Chenb3561512017-11-21 18:07:17 -0800188 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800189 void noteMatcherMatched(const ConfigKey& key, const int64_t& id);
Yao Chenb3561512017-11-21 18:07:17 -0800190
191 /**
Bookatz8f2f3d82017-12-07 13:53:21 -0800192 * Report that an anomaly detection alert has been declared.
193 *
194 * [key]: The config key that this alert belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800195 * [id]: The id of the alert.
Bookatz8f2f3d82017-12-07 13:53:21 -0800196 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800197 void noteAnomalyDeclared(const ConfigKey& key, const int64_t& id);
Bookatz8f2f3d82017-12-07 13:53:21 -0800198
199 /**
Yao Chenb3561512017-11-21 18:07:17 -0800200 * Report an atom event has been logged.
201 */
202 void noteAtomLogged(int atomId, int32_t timeSec);
203
204 /**
Bookatz1d0136d2017-12-01 11:13:32 -0800205 * Report that statsd modified the anomaly alarm registered with StatsCompanionService.
206 */
207 void noteRegisteredAnomalyAlarmChanged();
208
209 /**
Yangster-mac932ecec2018-02-01 10:23:52 -0800210 * Report that statsd modified the periodic alarm registered with StatsCompanionService.
211 */
212 void noteRegisteredPeriodicAlarmChanged();
213
214 /**
David Chenc136f452017-11-27 11:52:26 -0800215 * Records the number of snapshot and delta entries that are being dropped from the uid map.
216 */
217 void noteUidMapDropped(int snapshots, int deltas);
218
219 /**
220 * Updates the number of snapshots currently stored in the uid map.
221 */
222 void setUidMapSnapshots(int snapshots);
223 void setUidMapChanges(int changes);
224 void setCurrentUidMapMemory(int bytes);
225
Chenjie Yub038b702017-12-18 15:15:34 -0800226 // Update minimum interval between pulls for an pulled atom
227 void updateMinPullIntervalSec(int pullAtomId, long intervalSec);
228
229 // Notify pull request for an atom
230 void notePull(int pullAtomId);
231
232 // Notify pull request for an atom served from cached data
233 void notePullFromCache(int pullAtomId);
234
David Chenc136f452017-11-27 11:52:26 -0800235 /**
Yao Chen884c8c12018-01-26 10:36:25 -0800236 * Records statsd met an error while reading from logd.
237 */
238 void noteLoggerError(int error);
239
240 /**
Yao Chenb3561512017-11-21 18:07:17 -0800241 * Reset the historical stats. Including all stats in icebox, and the tracked stats about
242 * metrics, matchers, and atoms. The active configs will be kept and StatsdStats will continue
243 * to collect stats after reset() has been called.
244 */
245 void reset();
246
247 /**
248 * Output the stats in protobuf binary format to [buffer].
249 *
250 * [reset]: whether to clear the historical stats after the call.
251 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800252 void dumpStats(std::vector<uint8_t>* buffer, bool reset);
Yao Chenb3561512017-11-21 18:07:17 -0800253
Yao Chenf5acabe2018-01-17 14:10:34 -0800254 /**
255 * Output statsd stats in human readable format to [out] file.
256 */
257 void dumpStats(FILE* out) const;
258
Chenjie Yub038b702017-12-18 15:15:34 -0800259 typedef struct {
260 long totalPull;
261 long totalPullFromCache;
262 long minPullIntervalSec;
263 } PulledAtomStats;
264
Yao Chenb3561512017-11-21 18:07:17 -0800265private:
266 StatsdStats();
267
268 mutable std::mutex mLock;
269
Yao Chen69f1baf2017-11-27 17:25:36 -0800270 int32_t mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800271
David Chenc136f452017-11-27 11:52:26 -0800272 // Track the number of dropped entries used by the uid map.
Yao Chen20e9e622018-02-28 11:18:51 -0800273 UidMapStats mUidMapStats;
David Chenc136f452017-11-27 11:52:26 -0800274
Yao Chenb3561512017-11-21 18:07:17 -0800275 // The stats about the configs that are still in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800276 // The map size is capped by kMaxConfigCount.
Yao Chen20e9e622018-02-28 11:18:51 -0800277 std::map<const ConfigKey, std::shared_ptr<ConfigStats>> mConfigStats;
Yao Chenb3561512017-11-21 18:07:17 -0800278
279 // Stores the stats for the configs that are no longer in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800280 // The size of the vector is capped by kMaxIceBoxSize.
Yao Chen20e9e622018-02-28 11:18:51 -0800281 std::list<const std::shared_ptr<ConfigStats>> mIceBox;
Yao Chenb3561512017-11-21 18:07:17 -0800282
283 // Stores the number of times a pushed atom is logged.
284 // The size of the vector is the largest pushed atom id in atoms.proto + 1. Atoms
285 // out of that range will be dropped (it's either pulled atoms or test atoms).
286 // This is a vector, not a map because it will be accessed A LOT -- for each stats log.
287 std::vector<int> mPushedAtomStats;
288
Yao Chenf6723df2018-01-08 15:11:58 -0800289 // Maps PullAtomId to its stats. The size is capped by the puller atom counts.
Chenjie Yub038b702017-12-18 15:15:34 -0800290 std::map<int, PulledAtomStats> mPulledAtomStats;
291
Yao Chen884c8c12018-01-26 10:36:25 -0800292 // Logd errors. Size capped by kMaxLoggerErrors.
293 std::list<const std::pair<int, int>> mLoggerErrors;
294
Bookatz1d0136d2017-12-01 11:13:32 -0800295 // Stores the number of times statsd modified the anomaly alarm registered with
296 // StatsCompanionService.
297 int mAnomalyAlarmRegisteredStats = 0;
298
Yangster-mac932ecec2018-02-01 10:23:52 -0800299 // Stores the number of times statsd registers the periodic alarm changes
300 int mPeriodicAlarmRegisteredStats = 0;
301
Yao Chenb3561512017-11-21 18:07:17 -0800302
303 void noteConfigRemovedInternalLocked(const ConfigKey& key);
304
305 void resetInternalLocked();
306
Yao Chen0fac5b12017-11-28 16:07:02 -0800307 void noteDataDropped(const ConfigKey& key, int32_t timeSec);
308
309 void noteMetricsReportSent(const ConfigKey& key, int32_t timeSec);
310
311 void noteBroadcastSent(const ConfigKey& key, int32_t timeSec);
312
Yao Chen20e9e622018-02-28 11:18:51 -0800313 void addToIceBoxLocked(std::shared_ptr<ConfigStats>& stats);
Yao Chenf6723df2018-01-08 15:11:58 -0800314
Yao Chen69f1baf2017-11-27 17:25:36 -0800315 FRIEND_TEST(StatsdStatsTest, TestValidConfigAdd);
316 FRIEND_TEST(StatsdStatsTest, TestInvalidConfigAdd);
317 FRIEND_TEST(StatsdStatsTest, TestConfigRemove);
318 FRIEND_TEST(StatsdStatsTest, TestSubStats);
319 FRIEND_TEST(StatsdStatsTest, TestAtomLog);
Yao Chen0fac5b12017-11-28 16:07:02 -0800320 FRIEND_TEST(StatsdStatsTest, TestTimestampThreshold);
Bookatz1d0136d2017-12-01 11:13:32 -0800321 FRIEND_TEST(StatsdStatsTest, TestAnomalyMonitor);
Yao Chenb3561512017-11-21 18:07:17 -0800322};
323
324} // namespace statsd
325} // namespace os
Stefan Lafonc6f2fa22018-01-04 22:03:29 -0800326} // namespace android