blob: 767588808d45b1c6d30615b79cf6aca5abb8f1ef [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
Chenjie Yuc5875052018-03-09 10:13:11 -080084 // Per atom dimension key size limit
85 static const std::map<int, std::pair<size_t, size_t>> kAtomDimensionKeySizeLimitMap;
86
Yao Chenb3561512017-11-21 18:07:17 -080087 const static int kMaxConfigCount = 10;
Bookatz1476ef22018-02-13 12:26:01 -080088 const static int kMaxAlertCountPerConfig = 100;
Yao Chenb3561512017-11-21 18:07:17 -080089 const static int kMaxConditionCountPerConfig = 200;
90 const static int kMaxMetricCountPerConfig = 300;
91 const static int kMaxMatcherCountPerConfig = 500;
92
Yao Chenf6723df2018-01-08 15:11:58 -080093 // The max number of old config stats we keep.
94 const static int kMaxIceBoxSize = 20;
95
Yao Chen884c8c12018-01-26 10:36:25 -080096 const static int kMaxLoggerErrors = 10;
97
Yao Chen0fac5b12017-11-28 16:07:02 -080098 const static int kMaxTimestampCount = 20;
99
Yao Chend10f7b12017-12-18 12:53:50 -0800100 const static int kMaxLogSourceCount = 50;
101
David Chen4c6d97a2018-03-22 16:31:40 -0700102 // Max memory allowed for storing metrics per configuration. If this limit is exceeded, statsd
103 // drops the metrics data in memory.
104 static const size_t kMaxMetricsBytesPerConfig = 256 * 1024;
105
106 // Soft memory limit per configuration. Once this limit is exceeded, we begin notifying the
107 // data subscriber that it's time to call getData.
108 static const size_t kBytesPerConfigTriggerGetData = 128 * 1024;
David Chend9269e22017-12-05 13:43:51 -0800109
David Chenc136f452017-11-27 11:52:26 -0800110 // Cap the UID map's memory usage to this. This should be fairly high since the UID information
111 // is critical for understanding the metrics.
112 const static size_t kMaxBytesUsedUidMap = 50 * 1024;
113
David Chend9269e22017-12-05 13:43:51 -0800114 /* Minimum period between two broadcasts in nanoseconds. */
115 static const unsigned long long kMinBroadcastPeriodNs = 60 * NS_PER_SEC;
116
117 /* Min period between two checks of byte size per config key in nanoseconds. */
118 static const unsigned long long kMinByteSizeCheckPeriodNs = 10 * NS_PER_SEC;
119
yro98a28502018-01-18 17:00:14 -0800120 // Maximum age (30 days) that files on disk can exist in seconds.
121 static const int kMaxAgeSecond = 60 * 60 * 24 * 30;
122
123 // Maximum number of files (1000) that can be in stats directory on disk.
124 static const int kMaxFileNumber = 1000;
125
126 // Maximum size of all files that can be written to stats directory on disk.
127 static const int kMaxFileSize = 50 * 1024 * 1024;
128
Chenjie Yufa22d652018-02-05 14:37:48 -0800129 // How long to try to clear puller cache from last time
130 static const long kPullerCacheClearIntervalSec = 1;
131
Yao Chenb3561512017-11-21 18:07:17 -0800132 /**
133 * Report a new config has been received and report the static stats about the config.
134 *
135 * The static stats include: the count of metrics, conditions, matchers, and alerts.
136 * If the config is not valid, this config stats will be put into icebox immediately.
137 */
138 void noteConfigReceived(const ConfigKey& key, int metricsCount, int conditionsCount,
139 int matchersCount, int alertCount, bool isValid);
140 /**
141 * Report a config has been removed.
142 */
143 void noteConfigRemoved(const ConfigKey& key);
144
145 /**
146 * Report a broadcast has been sent to a config owner to collect the data.
147 */
148 void noteBroadcastSent(const ConfigKey& key);
149
150 /**
151 * Report a config's metrics data has been dropped.
152 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800153 void noteDataDropped(const ConfigKey& key);
154
155 /**
156 * Report metrics data report has been sent.
157 *
158 * The report may be requested via StatsManager API, or through adb cmd.
159 */
160 void noteMetricsReportSent(const ConfigKey& key);
Yao Chenb3561512017-11-21 18:07:17 -0800161
162 /**
163 * Report the size of output tuple of a condition.
164 *
165 * Note: only report when the condition has an output dimension, and the tuple
166 * count > kDimensionKeySizeSoftLimit.
167 *
168 * [key]: The config key that this condition belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800169 * [id]: The id of the condition.
Yao Chenb3561512017-11-21 18:07:17 -0800170 * [size]: The output tuple size.
171 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800172 void noteConditionDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800173
174 /**
175 * Report the size of output tuple of a metric.
176 *
177 * Note: only report when the metric has an output dimension, and the tuple
178 * count > kDimensionKeySizeSoftLimit.
179 *
180 * [key]: The config key that this metric belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800181 * [id]: The id of the metric.
Yao Chenb3561512017-11-21 18:07:17 -0800182 * [size]: The output tuple size.
183 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800184 void noteMetricDimensionSize(const ConfigKey& key, const int64_t& id, int size);
Yao Chenb3561512017-11-21 18:07:17 -0800185
186 /**
187 * Report a matcher has been matched.
188 *
189 * [key]: The config key that this matcher belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800190 * [id]: The id of the matcher.
Yao Chenb3561512017-11-21 18:07:17 -0800191 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800192 void noteMatcherMatched(const ConfigKey& key, const int64_t& id);
Yao Chenb3561512017-11-21 18:07:17 -0800193
194 /**
Bookatz8f2f3d82017-12-07 13:53:21 -0800195 * Report that an anomaly detection alert has been declared.
196 *
197 * [key]: The config key that this alert belongs to.
Yangster-mac94e197c2018-01-02 16:03:03 -0800198 * [id]: The id of the alert.
Bookatz8f2f3d82017-12-07 13:53:21 -0800199 */
Yangster-mac94e197c2018-01-02 16:03:03 -0800200 void noteAnomalyDeclared(const ConfigKey& key, const int64_t& id);
Bookatz8f2f3d82017-12-07 13:53:21 -0800201
202 /**
Yao Chenb3561512017-11-21 18:07:17 -0800203 * Report an atom event has been logged.
204 */
205 void noteAtomLogged(int atomId, int32_t timeSec);
206
207 /**
Bookatz1d0136d2017-12-01 11:13:32 -0800208 * Report that statsd modified the anomaly alarm registered with StatsCompanionService.
209 */
210 void noteRegisteredAnomalyAlarmChanged();
211
212 /**
Yangster-mac932ecec2018-02-01 10:23:52 -0800213 * Report that statsd modified the periodic alarm registered with StatsCompanionService.
214 */
215 void noteRegisteredPeriodicAlarmChanged();
216
217 /**
David Chenc136f452017-11-27 11:52:26 -0800218 * Records the number of snapshot and delta entries that are being dropped from the uid map.
219 */
220 void noteUidMapDropped(int snapshots, int deltas);
221
222 /**
223 * Updates the number of snapshots currently stored in the uid map.
224 */
225 void setUidMapSnapshots(int snapshots);
226 void setUidMapChanges(int changes);
227 void setCurrentUidMapMemory(int bytes);
228
Chenjie Yub038b702017-12-18 15:15:34 -0800229 // Update minimum interval between pulls for an pulled atom
230 void updateMinPullIntervalSec(int pullAtomId, long intervalSec);
231
232 // Notify pull request for an atom
233 void notePull(int pullAtomId);
234
235 // Notify pull request for an atom served from cached data
236 void notePullFromCache(int pullAtomId);
237
David Chenc136f452017-11-27 11:52:26 -0800238 /**
Yao Chen884c8c12018-01-26 10:36:25 -0800239 * Records statsd met an error while reading from logd.
240 */
241 void noteLoggerError(int error);
242
243 /**
Yao Chenb3561512017-11-21 18:07:17 -0800244 * Reset the historical stats. Including all stats in icebox, and the tracked stats about
245 * metrics, matchers, and atoms. The active configs will be kept and StatsdStats will continue
246 * to collect stats after reset() has been called.
247 */
248 void reset();
249
250 /**
251 * Output the stats in protobuf binary format to [buffer].
252 *
253 * [reset]: whether to clear the historical stats after the call.
254 */
Yao Chen69f1baf2017-11-27 17:25:36 -0800255 void dumpStats(std::vector<uint8_t>* buffer, bool reset);
Yao Chenb3561512017-11-21 18:07:17 -0800256
Yao Chenf5acabe2018-01-17 14:10:34 -0800257 /**
258 * Output statsd stats in human readable format to [out] file.
259 */
260 void dumpStats(FILE* out) const;
261
Chenjie Yub038b702017-12-18 15:15:34 -0800262 typedef struct {
263 long totalPull;
264 long totalPullFromCache;
265 long minPullIntervalSec;
266 } PulledAtomStats;
267
Yao Chenb3561512017-11-21 18:07:17 -0800268private:
269 StatsdStats();
270
271 mutable std::mutex mLock;
272
Yao Chen69f1baf2017-11-27 17:25:36 -0800273 int32_t mStartTimeSec;
Yao Chenb3561512017-11-21 18:07:17 -0800274
David Chenc136f452017-11-27 11:52:26 -0800275 // Track the number of dropped entries used by the uid map.
Yao Chen20e9e622018-02-28 11:18:51 -0800276 UidMapStats mUidMapStats;
David Chenc136f452017-11-27 11:52:26 -0800277
Yao Chenb3561512017-11-21 18:07:17 -0800278 // The stats about the configs that are still in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800279 // The map size is capped by kMaxConfigCount.
Yao Chen20e9e622018-02-28 11:18:51 -0800280 std::map<const ConfigKey, std::shared_ptr<ConfigStats>> mConfigStats;
Yao Chenb3561512017-11-21 18:07:17 -0800281
282 // Stores the stats for the configs that are no longer in use.
Yao Chenf6723df2018-01-08 15:11:58 -0800283 // The size of the vector is capped by kMaxIceBoxSize.
Yao Chen20e9e622018-02-28 11:18:51 -0800284 std::list<const std::shared_ptr<ConfigStats>> mIceBox;
Yao Chenb3561512017-11-21 18:07:17 -0800285
286 // Stores the number of times a pushed atom is logged.
287 // The size of the vector is the largest pushed atom id in atoms.proto + 1. Atoms
288 // out of that range will be dropped (it's either pulled atoms or test atoms).
289 // This is a vector, not a map because it will be accessed A LOT -- for each stats log.
290 std::vector<int> mPushedAtomStats;
291
Yao Chenf6723df2018-01-08 15:11:58 -0800292 // Maps PullAtomId to its stats. The size is capped by the puller atom counts.
Chenjie Yub038b702017-12-18 15:15:34 -0800293 std::map<int, PulledAtomStats> mPulledAtomStats;
294
Yao Chen884c8c12018-01-26 10:36:25 -0800295 // Logd errors. Size capped by kMaxLoggerErrors.
296 std::list<const std::pair<int, int>> mLoggerErrors;
297
Bookatz1d0136d2017-12-01 11:13:32 -0800298 // Stores the number of times statsd modified the anomaly alarm registered with
299 // StatsCompanionService.
300 int mAnomalyAlarmRegisteredStats = 0;
301
Yangster-mac932ecec2018-02-01 10:23:52 -0800302 // Stores the number of times statsd registers the periodic alarm changes
303 int mPeriodicAlarmRegisteredStats = 0;
304
Yao Chenb3561512017-11-21 18:07:17 -0800305
306 void noteConfigRemovedInternalLocked(const ConfigKey& key);
307
308 void resetInternalLocked();
309
Yao Chen0fac5b12017-11-28 16:07:02 -0800310 void noteDataDropped(const ConfigKey& key, int32_t timeSec);
311
312 void noteMetricsReportSent(const ConfigKey& key, int32_t timeSec);
313
314 void noteBroadcastSent(const ConfigKey& key, int32_t timeSec);
315
Yao Chen20e9e622018-02-28 11:18:51 -0800316 void addToIceBoxLocked(std::shared_ptr<ConfigStats>& stats);
Yao Chenf6723df2018-01-08 15:11:58 -0800317
Yao Chen69f1baf2017-11-27 17:25:36 -0800318 FRIEND_TEST(StatsdStatsTest, TestValidConfigAdd);
319 FRIEND_TEST(StatsdStatsTest, TestInvalidConfigAdd);
320 FRIEND_TEST(StatsdStatsTest, TestConfigRemove);
321 FRIEND_TEST(StatsdStatsTest, TestSubStats);
322 FRIEND_TEST(StatsdStatsTest, TestAtomLog);
Yao Chen0fac5b12017-11-28 16:07:02 -0800323 FRIEND_TEST(StatsdStatsTest, TestTimestampThreshold);
Bookatz1d0136d2017-12-01 11:13:32 -0800324 FRIEND_TEST(StatsdStatsTest, TestAnomalyMonitor);
Yao Chenb3561512017-11-21 18:07:17 -0800325};
326
327} // namespace statsd
328} // namespace os
Stefan Lafonc6f2fa22018-01-04 22:03:29 -0800329} // namespace android